Hi how can i generate a range of "double" numbers? For example how can i generate numbers between 2.50 and 7.20 There is a method in Random() class for "int" numbers Next(Int32, Int32) is there something similar for double?
Asked
Active
Viewed 9,921 times
3 Answers
8
You can write an extension method to Random for Random.NextDouble(double MinValue,double MaxValue) so that you can use it everywhere:
public static class RandomExtensions
{
public static double NextDouble(this Random RandGenerator, double MinValue, double MaxValue)
{
return RandGenerator.NextDouble() * (MaxValue - MinValue) + MinValue;
}
}

Boluc Papuccuoglu
- 2,318
- 1
- 14
- 24
3
Get a value from 0 to 1, then multiply it by 7.20 - 2.50
and add 2.50
.
double result = (random.NextDouble() * (7.2 - 2.5)) + 2.5;

ken2k
- 48,145
- 10
- 116
- 176
1
Yes, it's called Random.NextDouble()
. This returns a double
between 0 and 1.
var value = lower + (random.NextDouble() * (upper - lower))
will return what you need.

Roy Dictus
- 32,551
- 8
- 60
- 76