Kevin
Kevin

Reputation: 5694

Javascript Math.random()

Math.random() in javascript is able to return 1, right? Which means if I would be to use it to get a random index on my array the following code could fail:

var arr = [ 1, 2, 3 ],
    index = Math.floor(Math.random() * arr.length);

// index could be 3?
alert(arr[index]);

Could someone shed some light on this?

Upvotes: 3

Views: 3289

Answers (4)

Alnitak
Alnitak

Reputation: 339786

No, it returns from 0 inclusive to 1 exclusive

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

Note however the caveat in that page:

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for Math.random() itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 262) to calculate the usually-excluded upper bound.

For these purposes, though, you should be fine.

Upvotes: 8

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

The link you posted takes me to a site that says:

Returns a pseudo-random number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive). The random number generator is seeded from the current time, as in Java.

"inclusive" means the value is part of the range, whereas "exclusive" means that the value is not part of the range.

So Math.random() returns a value from 0 to just-less-than 1.

Upvotes: 8

MadBender
MadBender

Reputation: 1458

between 0 (inclusive) and 1 (exclusive) - cannot be 1

Your code is all right

Upvotes: 0

Thorben
Thorben

Reputation: 6981

I am pretty sure the number returned by

Math.random()

is smaller than 1 but equal or greater than zero.

Upvotes: 0

Related Questions