JS: Random Range Function

By Xah Lee. Date: . Last updated: .

How to generate a random number?

// generate a pseudo-random number between 0 to 1. (including 0 but excluding 1)

Math.random();

〔►see JS: Math Object

How to get a random real number between min and max?

// pre es2015

var xah_random_real = function (xmin,xmax) {
    // random real number in range {min, max}, including min but excluding max. 
    // version 2017-05-12
    return Math.random() * (xmax - xmin) + xmin;
};
// es2015
// random real number in range {min, max}, including min but excluding max. version 2017-05-12
const xah_random_real = ((xmin,xmax) => ( Math.random() * (xmax - xmin) + xmin));

How to get a random integer?

// pre es2015
var xah_random_int = function (xmin,xmax) {
    // random integer in range {min, max}, including min and max
    return Math.floor( Math.random() * (xmax + 1 - xmin) + xmin );
};
// es2015
// random integer in range {min, max}, including min and max
const xah_random_int = ((xmin,xmax) => (Math.floor( Math.random() * (xmax + 1 - xmin) + xmin ))) ;

How is random number seeded?

It's based on current time.

How to seed random number?

You can't.

Random Array Element, Randomize Array

JS: Random Array Element, Randomize Array

Like what you read? Buy JavaScript in Depth