Wrymn
Wrymn

Reputation: 193

c# Random number between Double.MinValue and Double.MaxValue

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?

Upvotes: 2

Views: 474

Answers (1)

Febre
Febre

Reputation: 135

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.

Upvotes: 5

Related Questions