How To Implement Own Random Number Generator In JavaScript Using LCG

The Linear Congruential Generator is a pseudo-random number generator. It is one of the simplest and most widely used algorithms of this type. It was developed by Donald Knuth in 1974 and it’s based on the linear congruential method.

The LCG algorithm generates a sequence of numbers from an initial value called the seed. Each successive member of the sequence is generated by multiplying the previous member by a fixed modulus, then adding an offset to the product. The modulus, multiplier and offset are stored in three integers ( m , c , a ) so that x = ma + c (mod m) , where x is the next number in sequence and x(i) = x(i-1) + c (mod m).

function LCG(seed) {
    this.seed = seed;
    this.multiplier= 1103515245;
    this.increment = 12345;
    this.modulus= 2147483648;

    this.next = function() {
        this.seed = (this.multiplier * this.seed + this.increment) % this.modulus;
        return this.seed;
    }

    this.nextFloat = function() {
        return this.next() / (this.modulus - 1);
    }

    this.nextRange = function(min, max) {
        return min + this.nextFloat() * (max - min);
    }

    this.nextRangeInt = function(min, max) {
        return Math.floor(min + this.nextFloat() * (max - min + 1));
    }

  }

//Create a new instance of the LCG

var lcg = new LCG(1);

var random = lcg.nextFloat();
console.log(random); //outputs 0.00000000046566128730773926


var random = lcg.nextRangeInt(0, 100);
console.log(random); //outputs 17 

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru