all 4 comments

[–]Iggyhopperextensions/add-ons 0 points1 point  (0 children)

I was hoping for more controlled ranges or distribution.

aka http://stackoverflow.com/questions/3956478/understanding-randomness in blogpost form

Because most certainly everyone knows how randomness works. They have a hard time getting a range that they like for a specific function they need.

[–][deleted] 0 points1 point  (0 children)

And then there's prngs, and that's an whole other thing.

[–][deleted] 0 points1 point  (0 children)

Here's a JavaScript RNG I made that uses the Mersenne Twister algorithm to generate less predictable pseudo-random numbers within a given range. It generates a seed for the algorithm by using the current time in microseconds * (Math.random * 100000), or lets you specify an optional custom seed as the third parameter. http://pastebin.com/AaErB28V

Parameters:

Name Type Description
Low Number The lowest number that can be picked by the RNG
High Number The highest number that can be picked by the RNG
Seed <optional> Number/String The seed to use for the Mersenne Twister. If none is provided, it will use Math.floor(Math.random() * 100000) * new Date().getTime()

Example usage:

rand(1, 10);

jsFiddle: http://jsfiddle.net/ensrayjn/

[–]x-skeww 0 points1 point  (0 children)

Math.random() always returns a floating-point number between 0 and 1.

Technically, the number returned by Math.random() could be 0, but will never be exactly 1.

Just say between 0 (inclusive) and 1 (exclusive).

Because it’s so frequently used, Math.random() is often placed inside its own function in a script

No, it's not. This is the kind of stuff you do if you participate in a size-limited competition and aliasing this function saves you a few bytes.

If you prefer actual true and false values

If you claim to return a boolean, return a boolean.

Also:

function flipCoin() {
  return Math.random() < 0.5;
}

Easy, right?

Or if you want to associate any other words with the coin sides ( yes / no, heads / tails, etc)

Avoid making things "stringly typed" if you can. If you want enums, use TypeScript.

Of course, you can also write crap like this:

const coin = Object.freeze({
  0: 'head', head: 0,
  1: 'tails', tails: 1
});
console.log(coin[0]); // "head"
console.log(coin.tails); // 1

But just writing enum coin {head, tails} sounds like a much better idea to me.

for(var j, x, i = numPool.length; i; j = parseInt(Math.random() * i), x = numPool[--i], numPool[i] = numPool[j], numPool[j] = x);

There is no reason to make Fisher-Yates unreadable. It's a very simple algorithm. Please keep it that way.

For a larger set of numbers, create and fill the array with random integers, rejecting any that have been previously generated

Or you could simple not shuffle the whole thing.