Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate random number between 0 and 1 in C#?

Tags:

I want to get the random number between 1 and 0. However, I'm getting 0 every single time. Can someone explain me the reason why I and getting 0 all the time? This is the code I have tried.

Random random = new Random(); int test = random.Next(0, 1); Console.WriteLine(test); Console.ReadKey(); 
like image 591
Alanay Avatar asked Jan 29 '17 19:01

Alanay


People also ask

How do you generate a random number between 0 and 1?

The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.

What does RAND () do in C?

rand() The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.


2 Answers

According to the documentation, Next returns an integer random number between the (inclusive) minimum and the (exclusive) maximum:

Return Value

A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

The only integer number which fulfills

0 <= x < 1 

is 0, hence you always get the value 0. In other words, 0 is the only integer that is within the half-closed interval [0, 1).

So, if you are actually interested in the integer values 0 or 1, then use 2 as upper bound:

var n = random.Next(0, 2); 

If instead you want to get a decimal between 0 and 1, try:

var n = random.NextDouble(); 

Hope this helps :-)

like image 198
Golo Roden Avatar answered Sep 20 '22 20:09

Golo Roden


You could, but you should do it this way:

double test = random.NextDouble(); 

If you wanted to get random integer ( 0 or 1), you should set upper bound to 2, because it is exclusive

int test = random.Next(0, 2); 
like image 27
Maksim Simkin Avatar answered Sep 20 '22 20:09

Maksim Simkin