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).
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).
1e15, for example, than not, and thus the probability of a number seemingly close to the upper bound being returned is high (or, put better, with the same number of digits), which is what I was trying to get across. Even though there is a uniform distribution. Thanks for pointing it out anyway.Math.ceil instead of floor?Slight modification of @user162097's answer
var getRandomIntWithLargestRange = () => Math.floor(
Number.MAX_SAFE_INTEGER * (2 * (Math.random() - 0.5))
);
// example
document.write(getRandomIntWithLargestRange());
Number.MIN_SAFE_INTEGER === -Number.MAX_SAFE_INTEGER): var r = getMaxRandomInt(); if (Math.random() < .5) r *= -1;
Number.MAX_VALUE*Math.random();I'm not quite sure what do you really want to achieve.Math.random()already has the max range of a float in Javascript. If you want, you can remove the decimal point, but either way it's still max range. To get more range than that, you would need some other type of number (not a native number type in JS). You can spin a random set of digits or character in a string as long as you'd like.BigInt, or 2^52 on V8 with a singleMath.random()call (which is why both existing answers are wrong, especially for Node).)