Sign in to follow this  

random doubles?

This topic is 3595 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3595 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this