Why does the Random.Next method in .NET support float / double?
There is a method .NextDouble()
that does almost what you want - just 0 to 1.0 instead of -1.0 to 1.0.
source to share
Because most of the time, we want to use int within a range, so we have been provided with methods for that. Many languages ​​only support a random method that returns a double between 0.0 and 1.0. C # provides this functionality in the .NextDouble () method.
This is a decent enough design as it makes it simple (Rolling a die - myRandom.Next (1,7);) and still possible. - myRandom.NextDouble () * 2.0 - 1.0;
source to share
You can use the Random.NextDouble () method which will generate a random value between 0.0 and 1.0 as suggested by @Joel_Coehorn
I just want to add that expanding the range to -1.0 and 1.0 is a simple calculation
var r = new Random();
var randomValue = r.NextDouble() * 2.0 - 1.0
Or, to generalize it to expand the result NextDouble()
to any range (a, b), you can do this:
var randomValue = r.NextDouble() * (b - a) - a
source to share