random doubles?

Started by
3 comments, last by SiCrane 16 years, 2 months ago
Whats a fast way to get a random double? I tried the code below but it breaks if the resulting int is too big... If I only multiply by 100 or 10 then I don't get the accuracy I need for some things...

double number= range_min + (rand()%(int)((range_max - range_min)*1000))/1000;

Advertisement
Well, rand() only returns values up to RAND_MAX. So you may want to randomly select a range of double values with one call to rand(), then select a random value within that range with a second call to rand()... or something like that. Simply multiplying a result by 10 or 100 doesn't increase the accuracy... you are still limited by the output space of rand().

EDIT:

Why not just do this?
double num = range_min + ((double)rand() / (double)RAND_MAX) * (range_max - range_min);


You're still limited, though, to RAND_MAX distinct values.
the reason I did *1000 ... /1000

is so say "1.567" becomes "1567" when I cast to int. every time I tried "rand()%1.567" I got an error that "1.567" is not an integer...

the problem isn't rand only returning a limiteed value. It's getting my double to an int so that % doesn't give an error without looseing precision...

I'll try your alternative way as that doesn't reley on a division remainder.
Another alternative is to use another algorithm that gives you doubles right away. A popular choice is Mersenne twister [wikipedia] which is quite fast and can output to different types. Near the bottom of the wikipedia-page is some links to implementations in different languages and some of them seem to have what you want.
Of course, there's also always boost::random.

This topic is closed to new replies.

Advertisement