DEV Community

Suprise Nkosi
Suprise Nkosi

Posted on • Edited on

Linear Congruential generator

This is a basic explanation of linear congruental generator, a method of generating random numerical values, the generating formulae is described by the equation

Xn+1 = (A x Xn+B) Mod M

A,B and M are constants
The value X used to initialize the sequence is called the seed. The sequence of numbers generated are random however they have a period in which the whole function repeat its values, making it a random but a predictable generator.

The implementation of this algorithm in javascript would be as follows

 var m =11, a =7, c =5; var z = 0; var rand = function(){ z=(a*z+c)%m; return z; }; for(i=0;i<20;i++){ console.log(rand()); } 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

So this might be a foundational piece of a more complex PRNG - as all of these are periodic, but the highly valued ones have periods long enough to not get hit in practice. Thanks!