Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will JavaScript random function ever return a 0 or 1?

Tags:

javascript

Can JavaScript's Math.random() ever return exactly a 0 or 1?

like image 795
SgtOJ Avatar asked Jul 30 '12 21:07

SgtOJ


People also ask

How to create random numbers in JavaScript?

JavaScript Random 1 Math.random (). Math.random () always returns a number lower than 1. 2 JavaScript Random Integers. Math.random () used with Math.floor () can be used to return random integers. There is no... 3 A Proper Random Function. As you can see from the examples above, it might be a good idea to create a proper random... More ...

How to return a random number between Min and Max in JavaScript?

This JavaScript function always returns a random number between min (included) and max (excluded): Example. function getRndInteger (min, max) {. return Math.floor(Math.random() * (max - min) ) + min; }.

How to make a random number equal to 0?

You can use Math.round (Math.random ()). If Math.random () generates a number less than 0.5 the result will be 0 otherwise it should be 1. Thank you for saving me brain cells. :) @Combine Should that be let oneOrZero = (Math.random ()>=0.5)? 1 : 0;? There is a +1 with Math.random, so it will always going to add 1 to the randomly generated number.

How to get the value of a random number in Python?

You can use Math.round(Math.random()). If Math.random() generates a number less than 0.5 the result will be 0 otherwise it should be 1.


2 Answers

Yes to 0, no to 1.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random

Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

like image 50
The Internet Avatar answered Oct 13 '22 01:10

The Internet


From the ECMAScript specification:

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.

Source: http://ecma-international.org/ecma-262/5.1/#sec-15.8.2.14

like image 29
Šime Vidas Avatar answered Oct 13 '22 00:10

Šime Vidas