Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Math.random() - parameter

What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)
like image 615
asifg Avatar asked May 17 '11 09:05

asifg


People also ask

Does Math random have parameters?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

What does Math random () * 100 do?

random will not return 1.0 itself, multiplying what Math. 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.

What does Math random () * 5 do?

Math. Random() returns a number between 0 and 1, excluding 1. So when you multiply it with 5, you get a number between 0 and 5 but not 5.

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

So you should use return Math. random() < 0.5; to have a (theoretical) 50/50 chance.


2 Answers

Math.random doesn't take params.

If you want to generate a random number between 2 intervals (a and b) you can use the formula:

math.random()*(b-a)+a
like image 165
CristiC Avatar answered Sep 20 '22 15:09

CristiC


Read the specification:

15.8.2.14 random ( )

Returns a number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

like image 35
RobG Avatar answered Sep 22 '22 15:09

RobG