Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Random function in c++

  1. Dec 2, 2009 #1

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


  2. jcsd
  3. Dec 2, 2009 #2


    User Avatar

    Staff: Mentor

    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: Dec 2, 2009
  4. Dec 2, 2009 #3


    User Avatar
    Gold Member

    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.
  5. Dec 2, 2009 #4


    User Avatar

    Staff: Mentor

    That may not work correctly for pseudorandom numbers, as bits in two consecutive numbers can be correlated.
  6. Dec 2, 2009 #5


    User Avatar
    Science Advisor
    Homework Helper

    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
  7. Dec 2, 2009 #6


    User Avatar
    Gold Member

    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).
  8. Dec 2, 2009 #7
    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.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Random function in c++
  1. Functions in c (Replies: 1)

  2. C++ random numbers! (Replies: 3)

  3. Random function in C (Replies: 31)