C++ Random?

Started by
31 comments, last by mpfeif101 20 years ago
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
Advertisement
My first recommendation is to check out boost::random.

However, you can get an approximate uniform random distribution by doing: (rand() % 10) + 1
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.
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?
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.

Thanks Salsa!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
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
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.
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.

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.
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?

This topic is closed to new replies.

Advertisement