[.net] [.NET] Random Float/Double
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?
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
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement