Reputation: 31
I am trying to generate uniformly distributed random numbers in an interval [a, b]
in c#. Can i use the
System.Random.Next(int min, int max)
method?
Upvotes: 1
Views: 582
Reputation: 186668
First of all you should create a generator, e.g.
// Simplest, but not thread safe
private static Random random = new Random();
then if you want an integer value uniformly distributed in [a, b]
range
// b + 1 since upper bound is excluded
int r = random.Next(a, b + 1);
if you require a floating point value (double
) uniformly distributed in [a, b)
range (border b
will be excluded)
double v = a + (b - a) * random.NextDouble();
Upvotes: 1