22. Random doubles

The following NextDouble extension method uses the Random class's existing NextDouble method to generate a double value within a range:

public static class RandomExtensions
{
// A Random objects shared by all extensions.
private static Random Rand = new Random();

// Return a double between minValue and maxValue.
public static double NextDouble(this Random rand,
double minValue, double maxValue)
{
return minValue + Rand.NextDouble() * (maxValue - minValue);
}
}

The RandomExtensions class creates a Random object at the class level. That object is static, so it is available to all extension methods defined in this class.

If you create a new Random object without passing its constructor a seed value, the class uses the system's time to initialize the new object. If a method creates its own Random object and the main program calls that method many times very quickly, then some of the method calls' Random objects may be initialized with the same system time. That would make them all return the same sequence of random numbers, and that wouldn't be very random at all! That's why the RandomExtensions class uses a single static Random object for all of its methods.

The new version of the NextDouble method returns minValue plus a random value times maxValue – minValue. The random value lies between 0.0 and 1.0, so the result lies between minValue and maxValue.

Download the RandomDoubles example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157