Random Trick
// multiply math random by another math random:
const value = Math.random() * Math.random() * 10;
// This makes it less likely that `value` will be 10
// the more times you multiply, the less likely you will be to reach
// the maximum potential value
const value = Math.random() * Math.random() * Math.random() * 10;
I use this a fair amount when creating artwork with code. I’ll usually use a seeded random though for more control.
I was thinking about different icons I might use in a node based programming environment to denote this use of random and after a little futzing around created this series of histograms:
function rand(n = 1, f = 1) {
let value = 1;
for (let i = 0; i < n; i++) {
value *= Math.random();
}
// fixing the value so that it fits
// nicely as a key in the hash table
// hash = {
// 0.2: 5,
// 0.9: 8,
// etc...
// }
return value.toFixed(f);
}
function histo(n = 1, f = 2, off, iter = 1500, size = 70) {
const vals = {};
const canvas = document.createElement('canvas');
const c = canvas.getContext('2d');
canvas.width = canvas.height = size;
canvas.style.margin = '.5em';
document.body.appendChild(canvas);
for (let i = 0; i < iter; i++) {
const randNum = off ? off - rand(n, f) : rand(n, f);
if (vals[randNum] == null) {
vals[randNum] = 1;
} else {
vals[randNum]++;
}
}
c.fillStyle = '#ccc';
c.fillRect(0, 0, size, size);
c.strokeRect(0, 0, size, size);
for (let i in vals) {
const x = parseFloat(i) * size;
c.beginPath();
c.moveTo(x, size);
c.lineTo(x, size - vals[i]);
c.stroke();
}
}
histo();
histo(2);
histo(3, 2, 1);
histo(5, 2, 1);
histo(6, 2, 0, 500);