• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# Random number generating...

## Recommended Posts

how do I generate a random number? I tried rand(), but I can''t figure out how to set the maximum value.

##### Share on other sites

...
#include
...

my_function()
{
srand(time(NULL)); //seed the randomizer with the clock

...

//for a number say 1-6 of a dice roll
roll = (rand() % 6) + 1;
}

hope that helps.

MojoMonkey

##### Share on other sites
If you want N-1 to be the largest random number and 0 the smallest use: rand() % N. Don''t forget to call randomize().

##### Share on other sites
Ok this is just some words of wisdom from me bccause im bored
"did u know that computer carnt genrate random numbers!! they are psudo random numbers because nothing calculated can be random"
isnt that nice

~prevail by daring to fail~

##### Share on other sites
exactly! That''s why you seed the randomizing function with the clock. This will give you a different value everytime you try it. Unless time stops....

##### Share on other sites
Actually nothing is random even in real life. Scientist have taken interest in the randomizity of lava lamps, but even their variation depends on the conditions. If there was a big bang and there will be a big crunch the explosion will depend on the conditions of the energy and our universe might actually be repeating the same pattern over and over or it might change every time depending on the big crunch, think of dividing two figures, pii for example...

Here's a "randomizer" function I use :
  #include #include int rmi(int min,int max){static unsigned seed = 0;int figure;time_t sekond;if (seed==0) { time(&sekond); seed=(unsigned) ((sekond % UINT_MAX)+1); srand(seed); }figure = rand();figure = min + figure % (max - min + 1);return(figure);}

Edited by - Afterlife on August 8, 2001 5:03:03 PM

Edited by - Afterlife on August 8, 2001 5:05:43 PM

Edited by - Afterlife on August 8, 2001 5:06:50 PM

Edited by - Afterlife on August 8, 2001 5:07:31 PM

Edited by - Afterlife on August 8, 2001 5:08:14 PM

##### Share on other sites
Okay obviously none of you knows anything about the behavior of subatomic particles. Secondly using the modulus operator in attempting to set the upper bound on a "random" number greatly decreases the distribution associated with how "random" a number is in relation to prior calls to rand(). This may sound odd but its true.

Suppose you had a perfect random number generator, say p_rand(), that generated each integer from [0, RAND_MAX] equally as often. If you wanted a random number from [0, n) then you would execute p_rand()%n. From our original assumption we know p_rand() has a perfect distribution in [0, RAND_MAX] but does p_rand()%n have even a good distribution in [0, n)? A less than perfect distribution would create some numbers more often than others making your results hardly random.

Let''s look at the % operator. A call to p_rand()%2 would map each even integer to 0 and each odd integer to 1. If RAND_MAX is even then there are (RAND_MAX/2)+1 even integers and RAND_MAX/2 odd integers. The call to p_rand()%2 generates a 0 slightly more often than a 1. Well no problem you say just make RAND_MAX odd. 0 and 1 now occur at the same frequency but what if p_rand()%3 is executed? If RAND_MAX is not multiple of three we will have the same problem as before: certain integers will occur more often than others, throwing off our perfect random number generator. Obviously RAND_MAX can''t be changed for each % on each p_rand() call (its #define''d in stdlib.h).

As most of you pointed out there are no real random number generators on computers so p_rand() is just a fantasy. Programmers attempt to provide the best approximations possible and in these approximations some integers occur more often than others. This magnifies the problem of using % even more when trying to generate random numbers. Putting the approximation function rand() together with an unknown RAND_MAX and the % operator you can get some pretty unrandom results. Try running the following program on your platform:

#include
#include
#include
#include

int main()
{
srand((unsigned)time(0));
long even = 0, odd = 0;

for (long i = 0; i < LONG_MAX; ++i) // replace LONG_MAX if you don''t want to wait awhile
if (rand()%2 == 0) ++even;
else ++odd;

cout << "Even: " << (double)even/LONG_MAX << ''%'' << endl;
cout << "Odd: " << (double)odd/LONG_MAX << ''%'' << endl;

return 0;
}

For some applications--games--even a 45/55 split is unacceptable. Ever throw your controller at the TV yelling "This game is cheating!"?

If you want a good random number generator do a yahoo search for Blitz++. Its a good number crunching set of classes for math, physics, and even games. I''ve used it a few times in some AI programs with great success.

##### Share on other sites
Make that:

#include <iostream>
#include <limits>
#include <cstdlib>
#include <time>

##### Share on other sites
yes, and if you want to look behind the scenes try searching for "Mersenne Twister", it''s a random number generator which, if properly implemented, is ~4 times faster than good ol'' rand() .

##### Share on other sites
Even using srand() will not produce a fair distribution of randomly generated numbers!

I refer you to ''Numerical Recipes in C'', it gave me some lovely random number generators for my neural nets!

##### Share on other sites
Wouldn''t

(rand() / RAND_MAX) * 5.0;

produce more evenly distributed random numbers between 0 and 5, than rand() % 6?

##### Share on other sites
srand(time());uint rnum = rand();uint rnum2 = rnum;for (int i=0;i srand(rnum); rnum *= rand() / max;}

Would that work very well?

##### Share on other sites
quote:

Wouldn't
(rand() / RAND_MAX) * 5.0;
produce more evenly distributed random numbers between 0 and 5

Actually, that code produces a zero-mean process with zero entropy.

Edited by - Stoffel on August 14, 2001 5:55:58 PM

##### Share on other sites
its funny how u guys turn a simple random number generator into a complex algorithm

##### Share on other sites

Don''t use modulus (rand() % n) for random numbers. Some random number generators have problems for certain values of n. For instance, on my decstation rand() % 2 actually alternates 0 and 1, regardless of what you seed the random number generator with!

These kind of artifacts are actually fairly common. Use it was it was intended, by multiplying and rounding up or down.

##### Share on other sites
I use Shawn Cokus''s implementation of the Mersenne Twister in my GBA Lib I''m writing. There''s also Left Shift Register Combiners which produce randomish (sequence over 2^32 depending on start sequence) numbers even quicker. LSRC are usually covered in Cryptography. I haven''t looked at the Random Numbers in NR yet.

ICQ: 30514803
http://homepage.dtn.ntl.com/grahamr/

##### Share on other sites
quote:
Original post by ironfroggy
srand(time());uint rnum = rand();uint rnum2 = rnum;for (int i=0;i<rnum2;i++) { srand(rnum); rnum *= rand() / max;}

Would that work very well?

No, that would not work very well at all. I don''t really see what you''re doing, but doing repeated actions such as multiplication reduce the ''randomness'', and calling srand more than once in the same program is simply a bad idea unless you know exactly what you''re doing. (In this case, it''s almost entirely pointless.)

##### Share on other sites
I used the RAND_MAX solution long before I heard of the standard modulus solution. All you have to do is the following:

(float)rand() * (float)((float)MAX/(float)RAND_MAX);

And you can precompute the conversion factor (float)((float)MAX/(float)RAND_MAX) so that each number you generate requires only a multiplication, instead of a modulus division, which, I think (but am not entirely sure) is faster.

##### Share on other sites
quote:

a zero-mean process with zero entropy.

Strike three! I''m out! Didn''t understand a word of that sentence above.

Why wouldn''t the (rand() / RAND_MAX) * anything work?

- The "original" anonymous poster.

##### Share on other sites
quote:

a zero-mean process with zero entropy.

Strike three! I''m out! Didn''t understand a word of that sentence above.

Why wouldn''t the (rand() / RAND_MAX) * anything work?

##### Share on other sites
quote:
Original post by Anonymous Poster
Strike three! I'm out! Didn't understand a word of that sentence above.

Why wouldn't the (rand() / RAND_MAX) * anything work?

rand () returns an int between 0 and RAND_MAX-1, inclusive.
RAND_MAX is an integer.
Any integer divided by an integer that is greater than it produces zeros.
That statement will only produce zeros.

I just didn't want to come right out and say it, so I tried to insert a little information theory humor. Entropy is a way of measuring the amount of information in a process (the more random, the more information). I was going to say a zero-mean absolutely deterministic process, but I thought that would have been giving it away.

Only took a couple of days for someone to notice. *sigh*

EDIT: rand actually goes up to RAND_MAX, not RAND_MAX-1. So if you use the above algorithm, you will get a value of (multiplier) 1 time in every 32768 times with a uniform rand function, and 0 the rest of the time. Therefore it's not zero-mean, but it still has very low entropy. Sorry for the mix-up.

Edited by - Stoffel on August 15, 2001 4:31:51 PM

##### Share on other sites
quote:
Original post by Anonymous Poster
Why wouldn't the (rand() / RAND_MAX) * anything work?
Because dividing a number by another number larger than it yields a value between 0 and 1. And storing numbers like that in an int is just gonna give you 0. (There is technically an exception: when rand() returns RAND_MAX you'll get 1 instead of 0. That will occur about once in every 4 billion occurences or something like that. Edit #1: And before Stoffel says I'm wrong, MSDN says "The constant RAND_MAX is the maximum value that can be returned by the rand function." So, if I'm wrong, MSDN is wrong. Wouldn't be the first time. Edit #2: Heh... we were editing our messages at the same time. For all intents and purposes, you can pretty much assume it'll return zero all the time.)

Edited by - Kylotan on August 15, 2001 4:32:32 PM

Edited by - Kylotan on August 15, 2001 4:34:52 PM

##### Share on other sites
Edit: LMAO
Edit: ROFL
Edit: that was pretty funny.

Too bad there aren''t mutexes on web posts. =)

##### Share on other sites
After all the studying I did to solve concurrent programming problems, not once did I learn how to solve the issue of concurrent programmers

##### Share on other sites
Ok. Let''s make it really simple.

double random_number = rand();double denom = RAND_MAX;double result = (random_number / denom) * 50.0;cout << "Your random number (0-50): " << result << "\n";

And if you want just the integer part, you should round the number.

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627655
• Total Posts
2978460

• 10
• 12
• 22
• 13
• 33