Reputation: 2998
I want to generate uniform random numbers in Node.js with the largest range possible. What's the best way to go about doing this?
(By "largest possible" I mean something like 2^64 possibilities, not an infinite number of possibilities).
Upvotes: -1
Views: 1956
Reputation: 17168
Slight modification of @user162097's answer
var getRandomIntWithLargestRange = () => Math.floor(
Number.MAX_SAFE_INTEGER * (2 * (Math.random() - 0.5))
);
// example
document.write(getRandomIntWithLargestRange());
Upvotes: 0
Reputation: 1258
You can use the Number
object's MAX_SAFE_INTEGER
property, which was introduced in ES6 (there's also a polyfill for older versions of Node here) and gives the largest integer that will not collide with any other as the underlying numerical representation system loses accuracy. If, for whatever reason, you don't care about collisions, you could use the much larger MAX_VALUE
property on the same object. This is what I'd do:
// function declaration using ES6 arrow/lambda syntax
var getMaxRandomInt = () => Math.floor(Number.MAX_SAFE_INTEGER * Math.random());
// equivalent to the following:
// function getMaxRandomInt() { return Math.floor(Number.MAX_SAFE_INTEGER * Math.random()); }
// example
document.write(getMaxRandomInt());
Note that, though the distribution is uniform, most results will contain the same number of digits (or the same exponent, in scientific form) as the upper bound, given that there are many more large values than small. If you want to return a float, then you can just remove the Math.floor
function (though, functionally, there won't be much difference with large values, especially since all numbers are ultimately stored as floats in JavaScript).
Upvotes: 0