Advertisement

Randomize

Started by May 05, 2002 07:53 PM
13 comments, last by Ragadast 22 years, 4 months ago
How do you use the Randomize function (Rand) in C++?
Hehe this might be a little unclear, so I''ll explain:

Say you wanted to have a random number from 1 to 10.

First, you should seed the random number generator with something, preferably a time function, like timeGetTime(), or clock(), so it''s always different. Do this only once in the very beginning of your program.

Then, to get a random number, you would use the random function something like this:

rand()%10 would give you a random number from 1 to 10. (Or 0 to 9, I forget)

rand()%20 would give you ..... 1 to 20

if you want from other numbers than 0 or 1, you have to use math.

like if you want a number from 10 to 20, you should do something like

rand()%10 + 10;

get it? =D

-=Lohrno
Advertisement
Never use modulus with rand. Use division instead, or you''ll screw up even distribution:

int random_number = float(rand())/RAND_MAX*max;
int random_number = lower_bound+float(rand())/RAND_MAX*(upper_bound-lower_bound);
---visit #directxdev on afternet <- not just for directx, despite the name

  #include <stdlib.h>#include <iostream.h>#include <time.h>void main(){	srand( (unsigned)time( NULL ) );    // generate your random seed	cout << "Random number between 0 and 9: " << rand()%10 << endl;	cout << "Random number between 0 and 19: " << rand()%20 << endl;	cout << "Random number between 0 and 99: " << rand()%100 << endl;	cout << "Random number between 0 and 5000: " << rand()%5001 << endl;}  


EDIT: forget source brackets ;-)

[edited by - bangz on May 5, 2002 9:23:09 PM]
Can we do something like this?
-----
armorE = rand() % armorEP;
-----
Hi everyone!
quote: Original post by IndirectX
Never use modulus with rand. Use division instead, or you''ll screw up even distribution:


How would this affect the distribution?

<a href="http://www.purplenose.com>purplenose.com
Advertisement
How can you random, but then DONT get the same number again?
If I wanted to get a random number in plain ansi c,
would I also have to create a ´seed´ first or use the time function? if do, how would I go about doing this?
thanx in advance

PEACE
Carrot : if RAND_MAX == 10 and you call rand() % 3 the probability would be : 0=4 1=3 2=3. In the long run this makes for a big mistake and since that mistake is alway in the low number it imbalance things.

You should use this formula to have balanced probability :
Result = int(rand() / (RAND_MAX + 1.0f) * Delta)
If RAND_MAX was 10, random numbers would suck.

However on my machine it''s 32767, so what''s the problem?

This topic is closed to new replies.

Advertisement