Jump to content
  • Advertisement
Sign in to follow this  
Sync Views

random doubles?

This topic is 3898 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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!