Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct function using Math.random() to get 50/50 chance

Tags:

javascript

People also ask

How do you get a 50/50 chance in JavaScript?

The random number is either in the range [0,0.5) or [0.5,1) . So you should use return Math. random() < 0.5; to have a (theoretical) 50/50 chance.

What does math random () do?

The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.

What does math random () * 100 do?

random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99.

How do you calculate math random?

To create a random decimal number between two values (range), you can use the following formula: Math. random()*(b-a)+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.


Math.random():

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)

The random number is either in the range [0,0.5) or [0.5,1). So you should use return Math.random() < 0.5; to have a (theoretical) 50/50 chance.


The first one is the correct because the random number generators returns a number from 0 to 0.99999999 (depends on the exact accuracy of the generator itself)

So by splitting the values into two groups using the "<" operator, you should get two equal ranges:

[0 upto 0.49999999] and [0.5 upto 0.9999999]