Reputation: 545
It is the first time I ever post something here so be kind please :)
Here is my problem.
I'd like to use boost random number generator such as it is done in this example http://www.boost.org/doc/libs/1_46_1/libs/random/example/random_demo.cpp
The example works perfectly fine on my computer, the only problem is when I use it in a class I created, the outputs are all the same and I don't understand why since they're not in the example. The name of the class is called Edge and has two private members that are Point A,B (the classic example class). So you can see an "Edge" as a segment with end points A and B. My goal would be to draw a random point on this segment.
So when I do
int main(){
Edge test;
for (int i=0;i<10;i++)
std::cout << test.draw_a_double() << endl;
return 0;
}
It always returns the same numbers :(
Here is the method in the .h file:
double draw_a_Point();
Here are the "#includes" in the .cpp file (should I put those in the .h file by the way ? given that I don't use them in all the file of my project):
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
typedef boost::mt19937 base_generator_type;
Here is the code in my method:
base_generator_type generator(42u);
generator.seed(static_cast<unsigned int>(std::time(0)));
boost::uniform_real<> uni_dist(0,1);
boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
double diffChosen=uni();
return diffChosen;
I don't return a Point object here because the main and only problem comes from the fact that diffChosen is always the same.
Does the problem come from the fact that only in the main function the random number generator works ?
Thank you
Upvotes: 0
Views: 257
Reputation: 217145
Following may help:
double Edge::draw_a_double(base_generator_type& generator)
{
boost::uniform_real<> uni_dist(0,1);
boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
double diffChosen = uni();
return diffChosen;
}
int main()
{
base_generator_type generator(42u);
generator.seed(static_cast<unsigned int>(std::time(0)));
Edge test;
for (int i = 0; i < 10; i++) {
std::cout << test.draw_a_double(generator) << std::endl;
}
return 0;
}
Explanation of why your code fails:
generator
has an internal state to generate number.
You initialize this by seed
.
After returning a new random number, its state changes.
But you reset its state each time with:
generator.seed(static_cast<unsigned int>(std::time(0)));
std::time(0)
change each second...
So you get the same first number of the series of random numbers.
Upvotes: 1