Skip to content

Instantly share code, notes, and snippets.

@Protonk
Last active March 26, 2023 22:26
Show Gist options
  • Save Protonk/5389384 to your computer and use it in GitHub Desktop.
Save Protonk/5389384 to your computer and use it in GitHub Desktop.
Simple Linear Congruential Generator in Javascript
// A simple Linear Congruential Generator
// Establish the parameters of the generator
var m = 25,
// a - 1 should be divisible by m's prime factors
a = 11,
// c and m should be co-prime
c = 17;
// Setting the seed
var z = 3;
var rand = function() {
// define the recurrence relationship
z = (a * z + c) % m;
// return an integer
// Could return a float in (0, 1) by dividing by m
return z;
};
Copy link

ghost commented Mar 22, 2014

You could include range specifications. :)

@johanhelsing
Copy link

Thanks!

I modified and encapsulated the script a bit. If someone needs a predictable seedable rng, you can use this

function createRand(seed) {
  var m = 25;
  var a = 11;
  var c = 17;

  var z = seed || 3;
  return function() {
    z = (a * z + c) % m;
    return z/m;
  };
}

Usage:

var rand = createRand();
var a = rand() * 100;

@kalexmills
Copy link

kalexmills commented Jan 15, 2018

With the given parameters, it seems that dividing by m = 25 ensures you'll only ever see values of the form i / 25, where i is in [0, 24]...

Much larger primes are needed in general. See here for some suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment