15

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

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
SgtOJ
  • 569
  • 2
  • 10
  • 23
  • According to the documentation, Math.random() will return a number between 0 (inclusive) and 1 (exclusive). The important part is inclusive/exclusive. Inclusive means it's included, exclusive means it's not. So Math.random can return a 0 (because it's inclusive) but not a 1 (because it's exclusive) – Native Coder Jun 06 '17 at 23:14

4 Answers4

22

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

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • so. am I right to assume that randomly selecting an array element using random, would never select the final array value i.e Math.floor(Math.random() * namesArray.length) ?? – Hightower Jul 04 '19 at 23:36
  • 2
    @Hightower If there are 3 array elements, then `Math.random() * namesArray.length` will be a number in the range `[0, 3)`, which can be divided equally into `[0, 1)`, `[1, 2)`, and `[2, 3)`. If the number is in the last section, e.g., `2.4`, then `Math.floor` with result in `2` which is the index of the last array element. – Šime Vidas Jul 05 '19 at 14:10
7

Yes and No, in that order.

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.

Andrew Leach
  • 12,945
  • 1
  • 40
  • 47
3

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.

The Internet
  • 7,959
  • 10
  • 54
  • 89
3

It will not return 1

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.

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

Jory Cunningham
  • 744
  • 5
  • 6