Public
Edited
Jun 12, 2024
Importers
Insert cell
Insert cell
class Random {
constructor(s) {

function xmur3(str) {
for (
var i = 0, h = 1779033703 ^ str.length;
i < str.length;
i++
) {
h = Math.imul(h ^ str.charCodeAt(i), 3432918353)
h = (h << 13) | (h >>> 19)
}
return function () {
h = Math.imul(h ^ (h >>> 16), 2246822507)
h = Math.imul(h ^ (h >>> 13), 3266489909)
return (h ^= h >>> 16) >>> 0
}
}
function sfc32(a, b, c, d) {
return function () {
a |= 0
b |= 0
c |= 0
d |= 0
var t = (((a + b) | 0) + d) | 0
d = (d + 1) | 0
a = b ^ (b >>> 9)
b = (c + (c << 3)) | 0
c = (c << 21) | (c >>> 11)
c = (c + t) | 0
return (t >>> 0) / 4294967296
}
}
const hash = xmur3(s);
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number

this.prng = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, hash());
}

unit () {
return this.prng();
}
prob (p) {
return this.prng()<p ;
}
float(m, M) {
return this.prng()* (M-m) + m;
}
int(m, M) {
return Math.floor(this.prng()* (M-m) + m);
}
pick(arr) {
return arr[this.int(0, arr.length)];
}
fromObj(obj) {
const k = this.pick(Object.keys(obj));
return [k, obj[k]];
}
/**
* Sample `n` unique values from `arr`. If number of unique values in arr is less than n, it throws an error.
* @param n
* @param arr
* @returns
*/
uSample(n, arr) {
const vals = new Set(arr);
if (vals.size < n) throw 'Input array contain less unique values than the n argument!'
const s = new Set();
while (s.size < n) {
s.add(this.pick(arr));
}
return [...s.values()];
}
gauss(mean, stdDev) {
let u1, u2;
do {
u1 = this.prng();
u2 = this.prng();
} while (u1 === 0);
const z0 = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
return z0 * stdDev + mean;
}
weighted(arr, wei) {
wei.length = arr.length;
const ws = wei.reduce((a,w)=> a+w,0); // compute the sum of weights
const p = this.unit();
// wei.length = arr.length;
const nw = wei.reduce((ac, w, i) => (ac[i] =i===0? w / ws: ac[i-1]+ w/ws, ac), [0])
.filter(w => w<p);
return arr[nw.length];
}
rand2dens (m, M, df ) {
while(true) {
const pt = [this.float(m[0], M[0]), this.float(m[1], M[1])];
const prb = df(pt);
if (this.prob(prb)) return pt;
}
}

}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more