[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppSrand
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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.int main () { for (int i=0; i<10; ++i) { std::srand(0); std::cout << std::rand() << std::endl; } }
- include <iostream>
Having a 'random' seed
Use std::clock to set a seedint main() { std::srand(std::clock()); }
- include <iostream>
- include <ctime>
Setting the seed of the Boost random library
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); } }
- include <ctime>
- include <cassert>
- include <boost/random/normal_distribution.hpp>
- include <boost/random/lagged_fibonacci.hpp>
Code links
- ::, scope operator
- <<, stream out operator
- #include
- assert
- cassert (header file)
- ctime (header file)
- char
- clock
- const
- cout
- ctime (header file)
- double
- endl
- for
- iostream
- int
- long
- main
- return
- std
- std::cout
- std::endl
- std::rand
- rand, std::rand
- unsigned
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
