I have searched google through and no answer yet.
So question is, I need to create random generator API as following:
public static Double Range(Double minValue, Double maxValue)
{
return random.NextDouble() * (maxValue - minValue) + minValue; // random is just System.Random
}
everything works fine until I put Double.MinValue and Double.MaxValue into parameters, since it generates "infinite" invalid double (since the operation produces value out of 64bit double range).
Is there a way how to write the code so it can process and generate valid double even when Double.MinValue and Double.MaxValue are used?
Consider changing the logic of how you calculate the random double to something like
private static Double Range(Double minValue, Double maxValue)
{
var x = random.NextDouble();
return x * maxValue + (1 - x) * minValue;
}
The reason your one fails is because double.MinValue
would be negative, thus if you do maxValue - minValue
you are essentially doing double.MaxValue * 2
.