EN
JavaScript - random long value
5
points
In this short article, we would like to show to randomize long value using JavaScript.
Note: as long value we understand signed 64 bits integer value (from
-9223372036854775808
to9223372036854775807
), that must be stored usingBigInt
type according to JavaScriptNumber
type limits (max 53 bits signed integer numbers).
Quick solution:
// ONLINE-RUNNER:browser;
const randomLong = () => {
const a = BigInt(Math.floor(4294967296 * Math.random()));
const b = BigInt(Math.floor(4294967296 * Math.random()));
return (a << 32n) + b - 9223372036854775808n;
};
// Usage example:
console.log(randomLong()); // -6948466849156998830
console.log(randomLong()); // 5083666257616331386
console.log(randomLong()); // 6549344345629142903
Note:
BigInt
type was introduced around 2018-2020 in the major web browsers, and around 2018 in Node.js (v10.4.0).
LCG algorithm based solution
In this section, we use custom random numbers generator that is based on LCG (Linear congruential generator) algorithm.
// ONLINE-RUNNER:browser;
const createRandom = (seed) => {
const M = 18446744073709551616n; // modulus (max possible unsigned int64 value)
const A = 6364136223846793005n; // multiplier
const C = 1442695040888963407n; // incrementer
let R = BigInt(seed ?? Date.now()) % M;
return () => {
R = (R * A + C) % M;
return R - 9223372036854775808n; // conversion to signed int64 value
};
};
// Usage example (values should always be different):
const randomLong = createRandom();
console.log(randomLong()); // -3539040831513097570
console.log(randomLong()); // -5344103620952014571
console.log(randomLong()); // 300121421816388864
Note: used
M
,A
andC
parameters values comes from MMIX instruction designed by Donald Knuth.