Last active
March 26, 2023 22:26
-
-
Save Protonk/5389384 to your computer and use it in GitHub Desktop.
Simple Linear Congruential Generator in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
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;
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
You could include range specifications. :)