Updated on
To get a random double in a range in C#, we take Random.Shared.NextDouble(), which returns a value from 0.0 up to but not including 1.0, multiply it by the width of the range, and add the lower bound.
When the value has to be unpredictable, we build the same double from RandomNumberGenerator instead. Let’s look at both.
What Does NextDouble Return in C#?
NextDouble returns a random double that is at least 0.0 and always less than 1.0. Microsoft Learn’s reference page for the method describes the return value as “greater than or equal to 0.0, and less than 1.0”. In math notation, that is the half-open interval [0.0, 1.0).
The values are spread evenly across that interval. The .NET 11 runtime source shows Random.Shared and an unseeded Random building each double from the top 53 bits of a random 64-bit number. So the largest value we can ever get is 0.9999999999999999, one step below 1.0.
Because the interval is fixed, scaling it is simple. Multiply the result by any width, and the product still starts at zero and stops just short of that width.
NextDouble has no overload that takes bounds. If we want a double between two values, we write the scaling ourselves, which is what the rest of this article does.
To generate a pseudorandom double number we can use the NextDouble method from the Random class:
var rDouble = Random.Shared.NextDouble();
Random.Shared is a ready-made instance, so we don’t have to create our own with new Random(). Microsoft Learn describes it as “a thread-safe Random instance that may be used concurrently from any thread”. We cover it in more detail in our article on the Random class.
.NET 11 also adds a generic NextBinaryFloat<T>() method. For double, it returns exactly what NextDouble returns, so nothing in this article changes.
Generate a Secure Random Double
The RandomNumberGenerator class does not have a built-in method to generate a secure random double. In order to get a double between 0.0 and 1.0, we first create a secure random integer with the static GetInt32 method, and then divide it by int.MaxValue. Like every method in this article, it is a public static method of our console app’s Program class, next to Main, and it needs using System.Security.Cryptography; at the top of the file:
public static double GetSecureDouble()
{
var numerator = RandomNumberGenerator.GetInt32(int.MaxValue);
var sDouble = (double)numerator / int.MaxValue;
return sDouble;
}
GetInt32(int.MaxValue) returns a whole number from 0 up to int.MaxValue - 1. Dividing by int.MaxValue gives us a double that is at least 0.0 and less than 1.0, the same promise NextDouble makes. That is a little over two billion evenly spaced values, plenty for most uses, though fewer than the 53 bits NextDouble fills.
We don’t need to call RandomNumberGenerator.Create() first, either. GetInt32 is static.
Why not divide 1 by a random integer instead? Because the results pile up next to zero. With a random denominator between 2 and int.MaxValue, almost every result is smaller than one millionth, and scaling it to a range would leave us sitting on the lower bound.
RandomNumberGenerator can do a lot more than this, and our article on generating cryptographic random numbers with RandomNumberGenerator covers the rest.
Generate a Pseudorandom Double Within a Specified Range
The Random class provides a simple way to generate a double between 0 and 1. However, we want to get a number larger than 1 or less than zero within a custom range. Let’s accomplish this with our own custom method:
public static double GetPseudoDoubleWithinRange(double lowerBound, double upperBound)
{
var rDouble = Random.Shared.NextDouble();
var rRangeDouble = rDouble * (upperBound - lowerBound) + lowerBound;
return rRangeDouble;
}
We begin our custom method by generating a double with the NextDouble method. Notice that next we use a specific formula that modifies the double into the specified range. Multiplying the double value by the difference between the lowerBound and upperBound ensures that the double is below the upper bound, apart from one rounding corner case. Then we add the lowerBound which keeps the double at or above the lower bound.
Generate a Secure Random Double Within a Specified Range
We can create a secure double using the same formula and utilizing our custom GetSecureDouble method:
public static double GetSecureDoubleWithinRange(double lowerBound, double upperBound)
{
var rDouble = GetSecureDouble();
var rRangeDouble = rDouble * (upperBound - lowerBound) + lowerBound;
return rRangeDouble;
}
Now, if we want to use our custom methods, we can call them from Main in the same way we would as the methods within the Random class:
var pseudoDoubleWithinRange = GetPseudoDoubleWithinRange(16, 30000);
Console.WriteLine($"Pseudorandom double between 16 and 30000: {pseudoDoubleWithinRange}");
var secureDoubleWithinRange = GetSecureDoubleWithinRange(4, 123000);
Console.WriteLine($"Secure double between 4 and 123000: {secureDoubleWithinRange}");
Every run prints different numbers, but the output looks like this:
Pseudorandom double between 16 and 30000: 14370.320321794083 Secure double between 4 and 123000: 7010.292684733073
Can a Random Double Ever Equal the Upper Bound?
Yes, in rare cases. NextDouble never returns 1.0, but the multiplication and addition that follow are rounded to the nearest double. Rounding can land exactly on the upper bound.
The largest value NextDouble returns is 0.9999999999999999. Scale it to the range from 1 to 2, and the exact answer falls halfway between the two closest doubles, 1.9999999999999998 and 2. The rounding rules pick 2.
How often it happens depends on the bounds. Between 1 and 2, only that single largest value reaches 2, so we would need quadrillions of draws to see it once. When the bounds are large numbers and the range is narrow, it gets common.
Width has a limit as well. If upperBound - lowerBound is larger than double.MaxValue, the subtraction overflows to infinity, and the result is useless.
Neither case shows up in everyday ranges such as 16 to 30000, where even the largest NextDouble value lands below the upper bound.
We can watch both cases happen by running these lines in Main:
var largest = Math.BitDecrement(1.0); Console.WriteLine(largest); Console.WriteLine(largest * (2.0 - 1.0) + 1.0); Console.WriteLine(GetPseudoDoubleWithinRange(double.MinValue, double.MaxValue));
Math.BitDecrement gives us the closest double below its argument, which is the largest value NextDouble can return. We print with the invariant culture here. Under en-US, .NET shows the last line as ∞:
0.9999999999999999 2 Infinity
With bounds of 1,000,000,000,000,000 and one more than that, about one draw in 16 comes back equal to the upper bound (6,194 and 6,372 of 100,000 in two of our runs). Doubles that large sit 0.125 apart, so every NextDouble value from 0.9375 upwards rounds up.
If the upper bound must stay exclusive, we can step back by one value whenever we land on it:
public static double GetPseudoDoubleBelowUpperBound(double lowerBound, double upperBound)
{
var rRangeDouble = GetPseudoDoubleWithinRange(lowerBound, upperBound);
return rRangeDouble < upperBound ? rRangeDouble : Math.BitDecrement(upperBound);
}
For ranges wider than double.MaxValue, writing the formula as rDouble * upperBound + (1 - rDouble) * lowerBound keeps every step finite. Most code never needs either fix. We cover why doubles round like this in our article on floating-point types in C#.
That’s it, let’s summarize what we’ve learned.
Conclusion
The two main ways to generate random double numbers in a range in C# are the Random and RandomNumberGenerator classes. Random.Shared.NextDouble() gives us a value from 0.0 up to 1.0, and a secure integer from GetInt32 divided by int.MaxValue gives us the same interval from a cryptographic source. One formula scales either of them to any range, as long as we remember that rounding can touch the upper bound and that a range wider than double.MaxValue overflows.
If you want to achieve the same thing with integers, you can visit our article on how to generate random integers in C#.
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and MSTest 4.5.3.
