C++ Random Function: Generate Uniformly Distributed Numbers

  • Context: C/C++ 
  • Thread starter Thread starter omri3012
  • Start date Start date
  • Tags Tags
    C++ Function Random
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 7K views
omri3012
Messages
60
Reaction score
0
Hallo,

I'm looking for a Random function in c++. i tried to use in the function rand()% but
it does not generate a truly uniformly distributed random number in the span (since my span is large. 100000*100000). in other word it dosent generate a random number in equal probability in lage dimentions.
if you know a function or a way that i could generate random number in large span it would
be very helpful.

Thanks,

Omri
 
Physics news on Phys.org
That's because rand() generates numbers from 0..MAX_RAND range (and I think MAX_RAND is by default 32767). I remember seeing libraries for better pseudorandom number generators, shouldn't be difficult to google.
 
Last edited:
you could divide your range into 32767 zones and use rand() first to get a zone, then again to get a number within the zone. etc.
 
That may not work correctly for pseudorandom numbers, as bits in two consecutive numbers can be correlated.
 
harborsparrow said:
you could divide your range into 32767 zones and use rand() first to get a zone, then again to get a number within the zone. etc.
Which is roughly equivalent to calling rand() twice, multiplying the first one by RAND_MAX and then adding them.

If you need super random numbers you might want to look at a better rand library such as boost rand
Otherwise calling rand twice and shift+add might be ok
 
The standard rand() function is really bad and you'll run into problems very quickly (even for non-scientific applications like games).

An easy solution is to use a Mersenne twister generator instead. (There are some ready to use implementations linked at the bottom of the wiki page).
 
rand() is terrible and should not be used for anything even halfway serious. If you need a robust, fast, and accurate C++ random number generator you don't need to look any further than boost::random. You'll need to spend half an hour reading the docs in order to use it, but once you do it's a snap.