Home Communities
IT Knowledge
Inspiration
Languages
EN

# JavaScript - own random number generator (custom implementation)

14 points
Created by:
394

In this article, we're going to have a look at how to write own random numbers generator that is based on LCG (Linear congruential generator) algorithm in JavaScript.

## 1. Introduction

In JavaScript, we can implement a custom random number generator by using LCG (Linear congruential generator) algorithm. LCG is one of the oldest and best-known pseudorandom number generator algorithm. We can adjust this implementation to work on int or long.

Linear congruential generator is defined by the recurrence formula:

Where:

• `Xn+1` - new seed,
• `a` - multiplier,
• `Xn` - current seed (comes from previous calculations),
• `c` - incrementer,
• `m` - modulus (max integer value).

## 2. Implementation

Note: every time `randomInt()` method is called, it is necessary to update seed value.

``````// ONLINE-RUNNER:browser;

function CustomRandom(seed) {
var self = this;
if (seed == null) {
seed = Date.now();
}
var A = 1103515245; // multiplier
var C = 12345;      // incrementer
var M = 2147483647; // modulus == max integer value
self.nextInt = function() {
seed = (seed * A + C) % M;
return seed;
};
self.nextDouble = function() {
var value = self.nextInt();
return value / M;
};
}

// Usage example 1:

var random = new CustomRandom(3819201); // 3819201 is example initial seed

console.log(random.nextInt());  // 348328093
console.log(random.nextInt());  // 121065958
console.log(random.nextInt());  // 790325445

// Usage example 2 (values should be different always):

var random = new CustomRandom();

console.log(random.nextInt());  // 922892575
console.log(random.nextInt());  // 1117277734
console.log(random.nextInt());  // 2084933141

console.log(random.nextDouble());  // 0.6316955399847103
console.log(random.nextDouble());  // 0.5716405932659472
console.log(random.nextDouble());  // 0.3298228519641901``````