I’ve been ripping my hair out for a while now with these random numbers in C++.
In Python, I had the awesome:
random.uniform(0, 1)
Which churned out a new random number each time I called it.
C++ has to have something like this. I Googled for a long time, and found erand48(), which I plan to implement into my raytracer (I’m translating it from Python to C++).
I tried a simple test case, but I was hoping to create a random_uniform() function which always spits out a new random number (using time() isn’t going to work AFAICT, as this will be running really quickly)
unsigned short Xi[3] = {0, 1, 27};
std::cout << erand48(Xi);
And the output was (and will be every time I call the program):
0.174529
I tried using the previous output as the new Xi, like this (Xis initial value was defined):
float random_uniform() {
long generated = erand48(Xi);
int temp = generated * 1000000;
unsigned short Xi[3] = {temp - 16, temp - 7, temp - 18};
return generated;
}
But that doesn’t seem like it would generate random enough numbers (and it only spits out 0. I’, not sure why…).
Is there any way that I could make a function which spits out a new random number each time?
Not being familiar with python, I’m going to assume that random.uniform(0, 1) spits out a random number from a uniform distribution between 0 and 1?
If so, try the following:
Note that your mileage may vary though – rand() is not guaranteed to be a very high quality random number source. You may get visual artifacts depending on the implementation and how you’re using it. I use a Mersenne Twister random number generator in my raytracer.
EDIT: Just to be a little clearer, that’s:
If you call both
srandandrandat the same time, you’re likely to get the same “random” number each time, because unless thetimehas changed in the meantime you’ll seed the generator with exactly the same seed, and hence get exactly the same first random number.