[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppRand

(C++) std::rand

Function for drawing a random positive integer from zero to RAND_MAX. RAND_MAX is a #defined constant in cstdlib.

std::_lrand is like std::rand, except it returns random numbers in a larger range. Check out the Boost C++ library for other random number generators.

The code below draws 10 different random numbers.
  1. include <iostream>
int main() { for (int i=0; i!=10; ++i) { std::cout << std::rand() << std::endl; } }


As 'true' random number generation is impossible for a device as non-random as a computer, it uses this algorithm to mimic inpredictability as close as possible. This algorithm will always generate the same sequence from the same seed. The seed is the starting point of the rand sequence. The srand function sets this seed. The code below demonstrates that after the same seed (zero in this case), the first 'randomly drawn' number is always the same.

  1. include <iostream>
int main () { for (int i=0; i!=10; ++i) { std::srand(0); std::cout << std::rand() << std::endl; } }


Note when using multithreading

As srand and rand use a global/static variable and therefore is not suitable for multithreading. Check out the Boost C++ library for other random number generators that do support multithreading.

How to: get a broken random number from zero to one?

Knowing that std::rand has RAND_MAX as a maximum value, just divide by this value, after casting it to a double.

double uniform()
{
  return static_cast<double>(std::rand())/static_cast<double>(RAND_MAX);
}


How to: get a random number from a normal distribution?

See normal distribution.

'Rand' links

Code links



last edited (March 27, 2007) by bilderbikkel, Number of views: 9322, Current Rev: 23 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.