random integers

Started by
10 comments, last by Grain 18 years, 5 months ago
How do I assign an integer a random value?
-Mat² §alley©-
Advertisement
In what programming language?
C++, sorry.
-Mat² §alley©-

int n = rand();

?

Is that what you're referring to?

If so, make sure to set a new seed for the generator when you start the program or you'll always get the same random numbers. the seed usually comes in the form of the time.. either from when the operating system started, or real time of day.
You can use the rand function.

common usage:

int RandomNumber;
RandomNumber = rand();


You might wish to "randomize" the randomizer. For this you need to 'seed' the randomizer.

common method:

srand((unsigned)time(NULL));

rand/srand - include stdlib.h
time - include time.h

HTH

Chad
-ChadC
How to you confine it, for example, only give generate an integer between 1 and 10?
-Mat² §alley©-
The easiest way to do that is to use the modulus operator.

rand()%n gives a random number between 0 and n-1.
Its the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).
Quote:Original post by Anonymous Poster
Its the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).

More important is that many implementations of rand() aren't very good. They favor the high order bits in terms of randomness, but the modulo method uses the low order bits. This is an issue for any value of n.

A better method is
min + (int)(max*rand()/(RAND_MAX+1.0));
Alternatively, you could use a different RNG. boost provides several good ones, including ways of drawing from a range without messing with silly formulas.

CM
Some relavent links:

http://www.gamedev.net/community/forums/topic.asp?topic_id=157952
http://www.gamedev.net/community/forums/topic.asp?topic_id=219156

There are more, but you'll have to *search* for them ...

This topic is closed to new replies.

Advertisement