I realize this question has been asked countless times, but it seems that every answer does not take into account overflows.
The suggested method is as follows
public static double BoundedNext( double min, double max )
{
var random = new Random( Guid.NewGuid().GetHashCode() );
return ( random.NextDouble() * ( max - min ) ) + min;
}
In just about every single case, this works as it should. However, it does not properly handle cases where an overflow occurs, such as BoundedNext(Double.MinValue, Double.MaxValue)
. The issue becomes even trickier in languages like C#, where an overflowed double
equates to -/+ infinity
.
The simple solution would be to just use a larger type, but I would like a solution that is able to produce a random number between two numbers, for each explicit type, that can handle overflow cases.