Jump to content
  • Advertisement
Sign in to follow this  
Uphoreum

[.net] [.NET] Random Float/Double

This topic is 4158 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

I need to generate random decimal numbers from X negative value, to Y positive value. System.Random only generates whole numbers this way, and only generates doubles from 0.0 to 1.0. What can I use to generate a random floating point value ranging from negatives to positives?

Share this post


Link to post
Share on other sites
Advertisement
There's a great thread about mapping a range of numbers to another range of numbers here.

The basics are thusly:

First, find the range of numbers that you need. In your case, that'll be (Y - X), yielding a positive number (if X is negative, it'll be bigger than Y). We'll call this range 'Z'. Multiplying the random number gotten from System.Random's random double by Z, the new random number will be from 0 - Z.

Next comes the shifting of the range from 0 - Z to be from X - Y. To do so, simply add X to the number. The negativity of X will work itself out.

The snazzy thing is that this method works for both positive and negative values for X and Y, assuming Y is the larger of the two (more positive, not greater absolute value).

Best of luck!
-jouley

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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!