Add extension methods to the Random class to generate double values within a specified range in C#

The Random class provides methods for generating pseudo-random numbers. The Next method has three overloaded versions that produce a non-negative integer, an integer between 0 and some upper bound, and between lower and upper bounds.

Strangely the Random class's NextDouble method has only one version that returns a value between 0.0 and 1.0. This example adds the two other obvious versions to produce double values between 0.0 and an upper bound and between two bounds.

The following code shows the RandomExtensions class that implements the extension methods.

public static class RandomExtensions
{
    // Return a random value between 0 inclusive and max exclusive.
    public static double NextDouble(this Random rand, double max)
    {
        return rand.NextDouble() * max;
    }

    // Return a random value between min inclusive and max exclusive.
    public static double NextDouble(this Random rand, double min, double max)
    {
        return min + (rand.NextDouble() * (max - min));
    }
}

There are no big tricks here. The first method uses the original NextDouble method to get a value between 0.0 and 1.0. It multiplies that by the upper bound to get a value between 0.0 and the upper bound and returns that result.

The second method also uses the original NextDouble method to get a value between 0.0 and 1.0. It multiplies that by (max - min) and adds that to the lower bound. Because the random number generator gives a value between 0.0 and 1.0, the result is between:

    min + 0.0 * (max - min) = min

and

    min + 1.0 * (max - min) = min + (max - min) = max

The value is between 0.0 and 1.0 as desired so the method returns it.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.