Languages
[Edit]
EN

JavaScript - random long value

5 points
Created by:
Kevin
797

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 to 9223372036854775807), that must be stored using BigInt type according to JavaScript Number 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 and C parameters values comes from MMIX instruction designed by Donald Knuth.

 

See also

  1. JavaScript - random boolean value

  2. JavaScript - random byte value

  3. JavaScript - random short value

  4. JavaScript - random int value

  5. JavaScript - generate random long value as string

  6. JavaScript - own random number generator (custom implementation)

References

  1. BigInt - JavaScript - MDN Web Docs

Alternative titles

  1. JavaScript - random Int64 value
  2. JavaScript - random 64 bits signed int value
  3. JavaScript - random <-9223372036854775808, +9223372036854775807> value
  4. JavaScript - random slong value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join