I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?
In the C programming language, we have a function called rand, which helps in generating the random number. This function comes predefined in C and can be implemented in the program using stdlib. h header file.
rand() The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.
Computers can generate truly random numbers by observing some outside data, like mouse movements or fan noise, which is not predictable, and creating data from it. This is known as entropy. Other times, they generate “pseudorandom” numbers by using an algorithm so the results appear random, even though they aren't.
The only thing I'd add to Eric's response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). NextDouble
only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and range.
So, this would give us random doubles between 0.0 and 2.0:
rng.NextDouble() * 2.0
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
2.5 + rng.NextDouble() * 2.0
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
double NextDouble(Random rng, double min, double max) { return min + (rng.NextDouble() * (max - min)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With