chit
chit

Reputation: 31

How do i generate uniformly distributed random numbers in an interval [a, b] in c#

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

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

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

Related Questions