#### Archived

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

# C++ Random?

This topic is 5064 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

In PHP, random is very easy. To find a random number from 1-10 you simply put: rand(1,10); Do they have anything like this in C++, becuase the rand function in C++ gives you a random number from 0 to like 300000, lol Any help or links would be appreciated. Thanks, Matt

##### Share on other sites
My first recommendation is to check out boost::random.

However, you can get an approximate uniform random distribution by doing: (rand() % 10) + 1

##### Share on other sites
Once again, the low bits of the value returned by rand() are less random than the high bits, so the modulus operator should not be used in conjunction with it.

Just a practical caveat.

##### Share on other sites
Thanks for the help, but I''m just a newb. Is there a simpler way just to get a random (random meaning a different number every time unlike the C++ rand function) number between 1 and x?

##### Share on other sites
If you want a unique set of random numbers each time the program runs then you can seed srand() with the current time.

If you want a random number in the range [a, b] then you can use
a + (b - a) * (int)(rand() / (double)RAND_MAX)
if I have my math correct.

Colin Jeanne | Invader''s Realm
"I forgot I had the Scroll Lock key until a few weeks ago when some asshole program used it. It even used it right" - Conner McCloud

##### Share on other sites
If you don''t want to use boost::random, and think the low bit variance Oluseyi was talking about is significant, you can try:

(int)(((float)rand() / (RAND_MAX + 1)) * x) + 1

##### Share on other sites
quote:
Original post by Invader X
If you want a random number in the range [a, b] then you can use
a + (b - a) * (int)(rand() / (double)RAND_MAX)
if I have my math correct.

You need to add 1 to RAND_MAX in the denominator and add 1 to the (b - a) term.

##### Share on other sites
quote:
Original post by SiCrane
If you don''t want to use boost::random, and think the low bit variance Oluseyi was talking about is significant, you can try:

(int)(((float)rand() / (RAND_MAX + 1)) * x) + 1

I can tell you from experience that it''s very significant. If you plug the right constants in with the modulus operator, you can get repeating patterns with very short periods. Like, under half a dozen.

##### Share on other sites
quote:
Original post by Anonymous Poster
I can tell you from experience that it''s very significant. If you plug the right constants in with the modulus operator, you can get repeating patterns with very short periods. Like, under half a dozen.

You mean with your compiler and standard library. Not every rand() implementation is equal.

##### Share on other sites
quote:
Original post by SiCrane
You mean with your compiler and standard library. Not every rand() implementation is equal.

I''ve seen it on a couple different platforms, actually. You''re right that the problem isn''t as bad everywhere, though.

But knowing that, why would you recommend the method that gives poor results on some platforms when you could recommend the one that works well everywhere?

##### Share on other sites
quote:
Original post by Anonymous Poster
But knowing that, why would you recommend the method that gives poor results on some platforms when you could recommend the one that works well everywhere?

I did recommend one that works well everywhere: boost::random.

As for why I recommended the modulus method first amoungst the bad recommendations, the modulus method has the advantage that its easy to explain and easy to get mostly right. Contrast that with the ratio method. Consider Invader X''s attempt; it looks right at first glance but holds a pretty big bug: the probability of getting the max number is only one in RAND_MAX. Even corrected, it contains a number of casts and relies on implicit numeric type conversions which the slightest typo or ommission can cause to produce a bad range.

##### Share on other sites
Please recall that when using random numbers in C++, they will be the same each time the program is run- to generate truly random numbers that are different each time the program is run, you must #include <time.h> and seed your random numbers using srand().

- CD

// Brought to you by Code_Dark
| [( Politics Forum Beta-Test )]

##### Share on other sites
quote:
Original post by Code_Dark
...to generate truly random numbers...

Of course you didn't mean "truly random numbers", you meant "different pseudorandom numbers."

Just being a pedantic prick.

[edited by - bobstevens on April 13, 2004 11:56:53 AM]

##### Share on other sites
Is there an actual random seed you can put in, instead of time?

##### Share on other sites
Nothing portable.

You could always use a lava lamp or radioactive decay. There are very few true random processes in a computer.

Alterantely, you can try reading from /dev/rnd on most *nix machines, use the Crypto API''s GetRandom() on most Windows machines, Random() on Windows CE, etc. (But all of those are just pseduo-random number generators themselves.)

##### Share on other sites
Hmmm. I checked out the [url=http://www.boost.org/libs/random/index.html]boost random[/url], but as a I am a newb, I do not now how to get those headers on my computer. I know I have to save them onto my computer, but what about after that (I have Dev C++ in case that matters).

Thanks for all your help,
Matt

##### Share on other sites
Games that need predictable pseudorandom numbers use their own PRNGs, mostly table driven. Something to the effect of...
int GetRandom () { return random_array[(++randomptr)%tablesize]; }

Seeding then becomes setting "randomptr" with a table index. The table would be probably be generated with a normal rand() function.

##### Share on other sites
Once you''ve downloaded the boost headers, you can either put them in their own directory somewhere and add that directory to your include path, or you can try sticking them in a boost subdirectory of your current include directory. I personally prefer the former approach.

##### Share on other sites
Okay, I made a folder in "My Documents" called library. In there i made a folder called "boost" and in there I made a folder called "random". I uploaded the random.hpp file into the boost folder, and then I uploaded all the random generator files (boost/random/linear_congruential.hpp - boost/random/lagged_fibonacci.hpp) in the random folder. I then added the folder library to the includes. Which file should I include to get a random number?

Sorry for asking so many questions but thanks for anwering all of them .

- Matt

##### Share on other sites
You can use it like:
#include <boost/random/mersenne_twister.hpp>#include <boost/random/uniform_int.hpp>#include <boost/random/variate_generator.hpp>#include <iostream>int main(int, char **) {  boost::mt19937 rng;                       boost::variate_generator<boost::mt19937, boost::uniform_int<> >           d6(rng, boost::uniform_int<>(1, 6));  boost::variate_generator<boost::mt19937, boost::uniform_int<> >           d20(rng, boost::uniform_int<>(1, 20));  for (int i = 0; i < 4; i++) { // roll the d6 four times    std::cout << d6() << std::endl;  }  for (int i = 0; i < 4; i++) { // roll the d20 four times    std::cout << d20() << std::endl;  }  return 0;}

In this case I used a mersenne twister as a number source for a d6 and a d20. If I wanted to use a linear congruential generator I would have changed headers to <boost/random/linear_congruential.hpp> and changed rng from a boost::mt19937 to a boost::minstd_rand.

##### Share on other sites
you can use (rand() % anyNumber) to get a random number between 0 and anyNumber (or maybe anyNumber-1...im not sure).

##### Share on other sites
quote:
Original post by Anonymous Poster
you can use (rand() % anyNumber) to get a random number between 0 and anyNumber (or maybe anyNumber-1...im not sure).

...did you read anything anyone has written in this thread?

##### Share on other sites
the easiest way is:

srand((unsigned)time(NULL)); //at the start of the program

int r = rand%SomeNumber;//whenever you need a random number.

speaking of which does anyone know how to get a random floating point number between 0 and 1?

-----------------------------------------------------
Writer, Programer, Cook, I''m a Jack of all Trades
Current Design project: Ambitions Slave

##### Share on other sites
quote:
Original post by TechnoGoth
speaking of which does anyone know how to get a random floating point number between 0 and 1?

You could do it like several people have done above, namely.

value = rand()/((float)RAND_MAX) ;

##### Share on other sites

check out the mersenne twister for a very good pseudo random number generator.

pr0jekt2501