Improving on Javascript’s random numbers

Javascript’s lack of a good random numbers function is something that has always bothered me. No, I’m not talking about an extremely complex seedable psuedo-random number generator that optionally generates numbers from static interference in the Earth’s atmosphere or radio waves or whatever “real” random number generators do (see random.org for that). I’m simply talking about random numbers that are actually useful– e.g. random numbers between two other numbers, or what are called ranged random numbers.

Unfortunately, the only kind of random numbers Javascript’s Math library supplies are normalized random numbers (numbers from 0 to 1 only). To remedy this I’ve written a(nother) better random number generator that supplies random numbers within a range. Behold:

Math.randomRange = function(min, max) {
    if (min && max) {
        return (min + Math.floor(Math.random() * (max - min + 1)));
    } else if (min) {
        return (Math.floor(Math.random() * min + 1))
    } else {
        return (Math.floor(Math.random() * 101));
    }
}

If you include this function somewhere in your main JS file, you’ll be able to call Math.randomRange() just as you would Math.random(). The difference is that if you don’t pass in a range (minimum and maximum values), it returns a random number from 0-100. If you pass in just one value, it returns a random number from 0 to that variable. If you pass in both minimum and maximum values it returns a random number between those values.

Example usage:

for (var i = 0; i < 10; i++) {
    document.write(Math.randomRange() + "<br>");
}

document.write("<br>");

for (var i = 0; i < 10; i++) {
    document.write(Math.randomRange(50) + "<br>");
}

document.write("<br>");

for (var i = 0; i < 10; i++) {
    document.write(Math.randomRange(50, 100) + "<br>");
}

This function works with negative numbers, too:

for (var i = 0; i < 10; i++) {
    document.write(Math.randomRange(-100, 50) + "<br>");
}

Enjoy! If you think up something else awesome to add to this function, be sure to let me know via comment.

Leave a Reply

Your email address will not be published. Required fields are marked *