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

(C++) std::srand

The seed is the starting point of the std::rand sequence. std::srand() 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; } }


Having a 'random' seed

Use std::clock to set a seed
  1. include <iostream>
  2. include <ctime>
int main() { std::srand(std::clock()); }


Setting the seed of the Boost random library

  1. include <ctime>
  2. include <cassert>
  3. include <boost/random/normal_distribution.hpp>
  4. include <boost/random/lagged_fibonacci.hpp>
int main() { //A random number drawn from a normal distribution const double mean = 0.0; const double sigma = 1.0; boost::normal_distribution<double> norm_dist(mean, sigma); boost::lagged_fibonacci19937 engine; //Obtain a random seed std::srand(std::clock()); const unsigned long seed = std::rand(); //Must be of type unsigned long! //Set the seed engine.seed(seed); //Obtain the first value const double firstValue = norm_dist.operator () <boost::lagged_fibonacci19937>((engine)); //Obtain more random numbers for (int i=0; i<10; ++i) //Check 10 times { //Set the seed again engine.seed(seed); //Get a first temp value (why this is needed I don't know) const double temp = norm_dist.operator () <boost::lagged_fibonacci19937>((engine)); //Obtain the value that should be the same as firstValue const double value = norm_dist.operator () <boost::lagged_fibonacci19937>((engine)); assert(value==firstValue); } }


Code links



last edited (January 3, 2007) by bilderbikkel, Number of views: 5913, Current Rev: 15 (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.