473,804 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

rand() between m and n


Hi

I need help to generate some random numbers between 2 and 8.

#include <cstdlib>
using std::rand;

the following was out of my range,

int main() {

for (int i = 0; i < 50; i++){
int x = (int(rand())/444489786)*8;
cout << x << '\t' << endl;
}
}

it can be any quality random number.
thanks

Aug 1 '06
26 4113
Chris Theis wrote:
>
"Kai-Uwe Bux" <jk********@gmx .netwrote in message
news:ea******** **@murdoch.acc. Virginia.EDU...
>Chris Theis wrote:
>>>
<ar********** ******@gmail.co mwrote in message
news:11****** *************** *@h48g2000cwc.g ooglegroups.com ...
Hello all,
why you are going far away?
first use srand() to randomize radom number, srand get a parameter as
seed, like:
srand(3); or you can use srand(time(0));
then use this method to have randome number in a certain range:
x=minum number +rand()% maximum number;

Yes, that surely works but brings back my original comment. Using the
modulo operation you interfere with the randomness

How, and why?
>>and don't make use of the full period of the random generator.

Huh? I see that that can happen. However, I do not see why the
alternative of chopping [0,RAND_MAX] into n intervals of equal length it
a priory better.

Well we're getting into a hot topic here which has been discussed
extensively. On one hand using modulo you might skew the results towards
lower values
No mapping of [0,RAND_MAX+1) to [0,n) can produce truly uniform results
unless n divides RAND_MAX+1. To give correct probabilities you need to
throw away some results from rand().

and on the other hand you can have an effect on the
randomness. The reason is that the modulo operation uses low order bits
and depending on the type of random generator the high-order bits might
show better randomness. However, this is something which depends on the
implementation of rand
That's my point exactly. I do not oppose the statement that there are rand
implementations where modding is significantly worse than rescaling.
and is the subject of endless discussions! For a
thorough discussion on this including the mathematics you might refer to
Knuth's book The Art of computer programming Vol.2 and/or Numerical
Recipes.
>As far as I can see, any kind of mapping N values to n < N values can
tamper
with the period or other measures of randomness. Whether a particular
mapping fares better or worse depends on the underlying random number
generator.

Yes and no. Of course you will never get good results if your random
generator is crap. However, the simple scaling and offsetting does not
interfere with any property of the RNG and therefore does not affect the
"randomness ".
As a general statement, this seems false: simple scaling gives preference to
high order bits. If the rand() implementation uses a random number
generator whose higher order bits are less random than its lower order
bits, rescaling is worse than taking remainders. (Rumor has it, though,
that such weakness is less common among random number generators than crapy
low-order bits:-)
In opposition to this the modulo mapping can affect the randomness because
you're introducing a limitation.
[snip]

Best

Kai-Uwe Bux

Aug 3 '06 #21
"Pete Becker" <pe********@acm .orgwrote in message
news:ZM******** *************** *******@giganew s.com...
>
As I pointed out in another message, this doesn't compensate for
mismatched range sizes. The bias is less obvious than when using
remainainder because remainder puts the excess values down at the low end
of the target range, while the floating-point approach distributes them
more evenly. But try that code with a custom rand function that generates
values between 0 and 8, inclusive. One of the values will turn up twice as
often as the others. (I haven't done the analysis to figure out which
one.)

To avoid this bias, compute the largest multiple of the number of values
in the target range (m * (to - from + 1)) that is less than or equal to
the number of values in the generator's range (loosely, RAND_MAX+1, but
beware of overlows). Each time you call rand, check whether the value is
greater than or equal to this largest multiple; if it is, call rand again.
Hi Pete,

you're of course right about the introduction of a bias in both cases
(remainder and the floating point approach). However, I'm a bit sceptical
with respect to simply throwing away numbers above a certain threshold.
Depending on the situation (and the range) you might virtually shorten the
period of your RNG, which could introduce another problem. But I want to
emphasize that this depends very much on the situation.

There is one question that you might probably be able to answer. All RNG's
(Mersenne twister, RANMAR etc.) that we are using in the development of our
Monte Carlo simulations return values in the range from [0,1) which makes
sense from a mathematical point of view. I never quite figured why rand()
returns integer values. Probably you could shed some light on that.

Cheers
Chris
Aug 3 '06 #22

"Pete Becker" <pe********@acm .orgwrote in message
news:9-*************** *************** @giganews.com.. .
Chris Theis wrote:
>"Kai-Uwe Bux" <jk********@gmx .netwrote in message
news:ea******* ***@murdoch.acc .Virginia.EDU.. .
>>>
Huh? I see that that can happen. However, I do not see why the
alternativ e
of chopping [0,RAND_MAX] into n intervals of equal length it a priory
better.


Well we're getting into a hot topic here which has been discussed
extensively. On one hand using modulo you might skew the results towards
lower values and on the other hand you can have an effect on the
randomness. The reason is that the modulo operation uses low order bits

That's not the reason. Consider a drastically simplified case: a rand()
function that produces values between 0 and 5 inclusive, and an attempt to
generate values from 0 to 4 inclusive. Using the remainder operator (C and
C++ do not have a modulus operator, but for positive arguments remainder
and modulus do the same thing), the generated value 0, 1, 2, 3, and 4 each
map to themselves, and the generated value 5 maps to 0. So you get twice
as many 0's in the output.

When you use floating point, you're still mapping six values into five
slots, and one of the slots will come up twice as often as the others. Try
it.
[SNIP]

Sorry, but I'm not quite sure I understand what you mean by "using floating
point". If you do the scaling as I've said in one of my previous posts I
very much doubt that I would get one of the slots twice as often as the
others. Running a simple program like the one below shows a (more or less)
uniform distribution. Of course this is no relevant hypothesis test for
distributions nor one of the DIE-hard tests for RNGs!

int randam(int from, int to) {
return static_cast<int >( from + ( (to - from) * (rand() / (RAND_MAX +
1.0)) ));
}

int main() {
map<int, unsigned longHisto;
srand( 0 );
for( unsigned long i = 0; i < 10000000; ++i)
Histo[ randam( 0, 6)]++;

for( map<int, unsigned long>::iterator Iter = Histo.begin(); Iter !=
Histo.end(); ++Iter )
cout << Iter->first << ": " << Iter->second << endl;

return true;
}

Probably I missunderstood your point with respect to the statement that one
of the slots should come up twice as often.

Cheers
Chris
Aug 3 '06 #23
In article <87************ @localhost.loca ldomain>, ph****@yahoo.co m
says...

[ ... ]
I need help to generate some random numbers between 2 and 8.
This has been discussed a number of times in the past. One method
that works reasonably well looks like this:

#include <stdlib.h>

int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;

do {
retval = rand() / divisor;
} while (retval limit);

return retval;
}

int rand_lim(int lower, int upper) {
int range = abs(upper-lower);

return rand_lim(range) + lower;
}

This doesn't use floating point, doesn't introduce skew, and normally
uses the more significant bits of the value returned by rand(), which
are generally at least as random as the less significant bits (in
some cases they're about equal, with a linear congruential generator,
the upper bits are usually more random). Yes, in theory you _could_
create a generator in which the upper bits were inferior, (if nothing
else by simply swapping bits) but I've never actually seen such a
thing.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 3 '06 #24
Chris Theis wrote:
>
Probably I missunderstood your point with respect to the statement that one
of the slots should come up twice as often.
That was in regard to the specific example I gave. Try it.
Aug 4 '06 #25
Kai-Uwe Bux wrote:
>
As a general statement, this seems false: simple scaling gives preference to
high order bits. If the rand() implementation uses a random number
generator whose higher order bits are less random than its lower order
bits, rescaling is worse than taking remainders. (Rumor has it, though,
that such weakness is less common among random number generators than crapy
low-order bits:-)
Not rumor, well established fact. Of course, it's possible that things
have changed in the twenty years or so since the usually-quoted tests
were made.
Aug 4 '06 #26
Chris Theis wrote:
>
There is one question that you might probably be able to answer. All RNG's
(Mersenne twister, RANMAR etc.) that we are using in the development of our
Monte Carlo simulations return values in the range from [0,1) which makes
sense from a mathematical point of view. I never quite figured why rand()
returns integer values. Probably you could shed some light on that.
It's fast and simple. And the canonical implementation of mersenne
twister also returns integer values. Floating-point math will rarely be
as fast as integer math, so when speed matters, integral random number
generators will usually be better.
Aug 4 '06 #27

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
4228
by: Tom McCallum | last post by:
Can any tell me why rand() is such a bad pseudo-random number generator. In all the articles I have read they say that you can predict the outcome of rand() but when I used its output with NIST's random number testsuite it passed all of the tests thrown at it for randomness. Can anyone suggest a test I could use that it would fail? A pointer to a suitable article would be appreciated. Thanks for your help in advance, Tom
7
3251
by: Chris Gordon-Smith | last post by:
I have a simulation program that calls the rand() function at various points while it executes. For the user interface that displays statistics etc. while the program runs, I use the Lazarus GUI library, which is based on GTK. Depending on which libraries I link in, I can have either a GTK1 or GTK2 user interface. I'm finding that the simulation behaves differently depending on whether I link with GTK1 or GTK2.
36
7144
by: Ben Justice | last post by:
For a program in c, I need some random numbers for a system were people are placing bets. This is not a commerical project btw. Generally, I tend to rely on things from the standard library, because they're written by people with skills far above mine. Hence, I've always used rand() and FALSELY assumed it could produce unpredictable random numbers and could be used in many situations even if security was an issue. Firstly, lets assume...
36
2696
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
8
4399
by: Jack | last post by:
When I use rand(), is the RAND_MAX value how long I am guaranteed that the same value will not appear twice? And is this a floating window? For example, if RAND_MAX is 32767, and I make 500,000 consecutive rand calls then is the rand() algorithm going to guarantee me that no floating window of calls over that 500,000 rand calls will have the same value twice? The only way that would work is if the series was identical everytime.
4
2798
by: Siam | last post by:
Hi all, I'm writing a shell language in c++ that supports the generation of random numbers, and by its nature, each command must be executed in a new thread. The call to the random function from my language simply propogates up to the rand( ) function from c++. For some reason, C++ will give each thread independent use of their own rand( ) function, so that a rand( ) call from one thread won't affect another thread's call to rand( )....
13
3673
by: Spiros Bousbouras | last post by:
The standard says that rand() should return a pseudo-random number but what does pseudorandom mean ? If an implementation of rand() always returned the same number would it be conforming ? What if it always alternated between 2 values ? On the practical side do you have any thoughts on what one could realistically expect from the behaviour of rand() ? Could for example one expect that eventually any value in the range will be returned ?
5
2326
by: ds | last post by:
Hi all, rand() is not thread safe, a fact that may not be so bad after all.. However, I face the following problem: a piece of code uses rand() to get a random sequence, but always seeds with the same seed for reproducibility of the results. Now I am porting this (old C89) code and have setup a nice app with threads that drives on one thread the old code and on another the new code, so that I can compare the results and see that nothing...
10
3023
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
15
3949
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10099
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7643
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4314
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3836
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3003
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.