Your scaling wouldn't work, because the scaling factor would be actually bigger than double.MaxValue which doesn't work.
var number = r.NextDouble() * 2d - 1d; // r in [-1, 1]
return number * double.MaxValue;
This code snippet first generates a uniform distributed random number in the range [-1,1].
Than it transforms it into your desired range.
This only works, when both ranges are equal, which is true for your use-case ( double.MaxValue == Math.Abs(double.MinValue)
)
Note: actually the upper bound of Random.NextDouble() is 0.99999999999999978 according to https://learn.microsoft.com/en-us/dotnet/api/system.random.nextdouble?view=netframework-4.7)
According to your question, how to get a range where 1 is included, you could implement the random.NextDouble()
method on your own.
The reference implementation (http://referencesource.microsoft.com/#mscorlib/system/random.cs,bb77e610694e64ca) uses the Random.Next() method and maps it to a double, where the Random.Next()
method has a range [0, Int32.MaxValue - 1]
. So just use r.Next() * (1.0 / (Int32.MaxValue - 1))
which would return double values in the range [0, 1]
.
By the way, I don't think, the docs are correct, since the maximum value, Random.NextDouble()
can generate is 0.999999999534339
, which is (Int32.MaxValue - 1) * (1.0 / Int32.MaxValue)
and not 0.99999999999999978
.