xxxxxxxxxx
127
function middleSquare4() {
let seed = 9385;
let myRandom = function() {
seed = (seed * seed).toString();
while (seed.length < 8) {
seed = '0'+seed;
}
seed = seed.substr(2, 4);
seed = parseInt(seed);
return seed / 10000;
}
return myRandom;
}
function middleSquare6() {
var seed = 987654;
let myRandom = function() {
seed = (seed * seed).toString();
while (seed.length < 10) {
seed = '0'+seed;
}
seed = seed.substr(2, 6);
seed = parseInt(seed);
return seed / 1000000;
};
return myRandom;
}
function lfsr() {
var value = 0x8988;
var tap1bit = 1;
var tap2bit = 9;
let myRandom = function() {
// taken from https://github.com/kirbysayshi/tetris-prng
var tap1val = (value >> tap1bit) & 1;
var tap2val = (value >> tap2bit) & 1;
var leftmostBit = tap1val ^ tap2val;
value = ((leftmostBit << 15) | (value >>> 1)) >>> 0;
return value / (2 ** 16);
};
return myRandom;
}
function logisticMap() {
var p = 0.1;
var r = 3.5;
let myRandom = function() {
p = r * p * (1 - p);
if (r < 3.96995) {
r += 0.00005;
}
return p;
};
return myRandom;
}
function xorshift() {
var state = 1;
let myRandom = function() {
// adapted from http://excamera.com/sphinx/article-xorshift.html
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
// javascript numbers overflow as negative, so map output to modulo
// plus 0.5
var ret = ((state % 100) / 200) + 0.5;
return ret;
}
return myRandom;
}
function jsBuiltin() {
return Math.random;
}
function p5jsBuiltin() {
return random;
}
// ---
// try to keep the code below unchanged (unless you have a really
// clever idea).
// ---
let currentRandom;
let sampleCount = 0;
let statusP;
let rselect;
let funcMap = {
'middle square 4': middleSquare4,
'middle square 6': middleSquare6,
'linear feedback shift register': lfsr,
'logistic map': logisticMap,
'xorshift': xorshift,
'Math.random()': jsBuiltin,
'p5js random()': p5jsBuiltin
}
function setup() {
createCanvas(400, 400);
background(0);
statusP = createP();
rselect = createSelect();
for (let key in funcMap) {
if (funcMap.hasOwnProperty(key)) {
rselect.option(key);
}
}
rselect.changed(function() {
currentRandom = funcMap[rselect.value()]();
sampleCount = 0;
background(0);
});
currentRandom = middleSquare4();
}
function draw() {
let xpos = currentRandom() * width;
let ypos = currentRandom() * height;
noStroke();
fill(255, 240);
ellipse(xpos, ypos, 10, 10);
fill(255);
statusP.html("samples: " + sampleCount);
sampleCount++;
}