# JavaScript Non-Linear Random Numbers

While normall dice toss will give you where n is the number of sides-of the dice.

this is an equal chance of each of the sides to come in 1 toss.

there are few easy ways of modifying a toss-result, using some of JavaScript’s native Math functions, such as modulus (%) and power (Math.pow), there are, naturally other that will work just as well, essentially once should choose a set of functions that will increase or modify the numeric value in a non-linear ‘way’, Math.pow is a good example since it may work exponentially, combined with modulus operation to keep the value ‘in-range’ we can play with JavaScript’s pseudo-random implementation to make some *cool variations of good old dice-toss..

*:cool? well.. if you’re a math-geek like me.. :)

# JavaScript and Canvas Playing : Generate Random Noise and Download The Image From The Canvas With New HTML5 Download Attribute + Demo

Generate some random noise (color or black&white) over canvas,

```<style type="text/css">
.random-gen-canvas-white {
width: 300px;
height: 300px;
background-color: rgba(255, 255, 255, .8);
outline: 1px solid rgba(0, 0, 0, .3);
box-shadow: 5px 5px 5px rgba(0, 0, 0, .2);
margin-bottom: 10px;
}
.btn {
width: 90%;
height: 50px;
margin: 2px 2px 2px 2px;
}
</style>
<canvas id="canvasWhite" class="random-gen-canvas-white" width="300" height="300"></canvas>
<script type="text/javascript">
function canvas_genRandomBNW() {
var canvas = document.getElementById("canvasWhite"),
ctx = canvas.getContext('2d'),
i, ii = 1200;
for (var i = 0; i < ii; i += 1) {
ctx.fillStyle = (~~(Math.random() * 2)) === 1 ? "rgba(255,255,255,.9)" : "rgba(0,0,0,.9)";
ctx.fillRect(~~(Math.random() * 300), //x
~~(Math.random() * 300), //y
1, 1);
}
return true;
}

function canvas_genRandomCOLOR() {
var canvas = document.getElementById("canvasWhite"),
ctx = canvas.getContext('2d'),
i, ii = 1200,
r, g, b, a;
for (var i = 0; i < ii; i += 1) {
r = (~~(Math.random() * 256)); //red
g = (~~(Math.random() * 256)); //green
b = (~~(Math.random() * 256)); //blue
a = "." + (30 + (~~(Math.random() * 71)))
.toString(); //alpha transparency from .30 to .90
ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
ctx.fillRect(~~(Math.random() * 300), //x
~~(Math.random() * 300), //y
1, 1);
}
return true;
}

function canvas_getImage() {
var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("target", "_blank");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png"));
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png"));
.toString(13) + ".png");
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png")
.replace('data:image/png;', 'data:application/octet-stream;'));
.toString(13) + ".png");
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

function canvas_clear() {
var canvas = document.getElementById("canvasWhite");
canvas.width = canvas.width;
}
</script>
<button class="btn btn-bnw" onclick="javascript:canvas_genRandomBNW();" type="button">Add Black&amp;White Noise!</button>
<button class="btn btn-color" onclick="javascript:window.canvas_genRandomCOLOR();" type="button">Add Color Noise!</button>
<button class="btn btn-getImage" onclick="javascript:window.canvas_getImage();" type="button">Open Image In New Tab!</button>
<button class="btn btn-clear" onclick="javascript:window.canvas_clear();" type="button">Clear</button>
```

here is the same code wrapped in PRE tag so WordPress will actually run it as a sample (nice and easy!)

```

function canvas_genRandomBNW(){var canvas=document.getElementById("canvasWhite"),ctx=canvas.getContext('2d'),i,ii=1200;for(var i=0;i<ii;i+=1){ctx.fillStyle=(~~(Math.random()*2))===1?"rgba(255,255,255,.9)":"rgba(0,0,0,.9)";ctx.fillRect(~~(Math.random()*300),~~(Math.random()*300),1,1);}
return true;}
function canvas_genRandomCOLOR(){var canvas=document.getElementById("canvasWhite"),ctx=canvas.getContext('2d'),i,ii=1200,r,g,b,a;for(var i=0;i<ii;i+=1){r=(~~(Math.random()*256));g=(~~(Math.random()*256));b=(~~(Math.random()*256));a="."+(30+(~~(Math.random()*71))).toString();ctx.fillStyle="rgba("+r+","+g+","+b+","+a+")";ctx.fillRect(~~(Math.random()*300),~~(Math.random()*300),1,1);}
return true;}
function canvas_getImage(){var canvas=document.getElementById("canvasWhite"),a=document.createElement("a");a.setAttribute("target","_blank");a.setAttribute("type","image/png");a.setAttribute("href",canvas.toDataURL("image/png"));document.getElementsByTagName("body")[0].appendChild(a);a.click(true);}
function canvas_clear(){var canvas=document.getElementById("canvasWhite");canvas.width=canvas.width;}

```

September 15th, 2016 - edit:

Some Log2 patterns
*plus a little trick to get a "better random" by reversing the digits.

```<!doctype html>
<html dir="ltr" lang="en-US">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="Content-Type"    content="text/html;charset=UTF-8"/>
<meta name="viewport"              content="width=device-width,height=device-height,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<style type="text/css" media="all">
html{
background: none lightblue;
}
</style>
<body>
<style type="text/css">
.random-gen-canvas-white {
width: 300px;
height: 300px;
background-color: rgba(255, 255, 255, .8);
outline: 1px solid rgba(0, 0, 0, .3);
box-shadow: 5px 5px 5px rgba(0, 0, 0, .2);
margin-bottom: 10px;
}
.btn {
width: 90%;
height: 50px;
margin: 2px 2px 2px 2px;
}
</style>
<canvas id="canvasWhite" class="random-gen-canvas-white" width="300" height="300"></canvas>
<script type="text/javascript">

function getRandom(modulo){
var number = Math.random();
number = String(number).substr(2,8).split('').reverse().join('');
number = Number(number);
number = Math.log2(1+1/number) / Math.log2(number);
number = String(number).replace(/[\,\.\-e]/gi,"");
number = Number(number);

return "undefined" === typeof modulo ? number : number % modulo;
}

function canvas_genRandomBNW() {
var canvas = document.getElementById("canvasWhite"),
ctx = canvas.getContext('2d'),
i, ii = 1200;
setTimeout(function(){
for (var i = 0; i < ii; i += 1) {
ctx.fillStyle = getRandom(2) === 1 ? "rgba(255,255,255,.9)" : "rgba(0,0,0,.9)";
ctx.fillRect(getRandom(300), //x
getRandom(300), //y
1, 1);
}
},20);
return true;
}

function canvas_genRandomCOLOR() {
var canvas = document.getElementById("canvasWhite"),
ctx = canvas.getContext('2d'),
i, ii = 1200,
r, g, b, a;
setTimeout(function(){
for (var i = 0; i < ii; i += 1) {
r = getRandom(256); //red
g = getRandom(256); //green
b = getRandom(256); //blue
a = "." + (30 + getRandom(71))
.toString(); //alpha transparency from .30 to .90
ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a + ")";
ctx.fillRect(getRandom(300), //x
getRandom(300), //y
1, 1);
}
},20);
return true;
}

function canvas_getImage() {
var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("target", "_blank");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png"));
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png"));
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

var canvas = document.getElementById("canvasWhite"),
a = document.createElement("a");
a.setAttribute("type", "image/png");
a.setAttribute("href", canvas.toDataURL("image/png")
.replace('data:image/png;', 'data:application/octet-stream;'));
document.getElementsByTagName("body")[0].appendChild(a);
a.click(true);
}

function canvas_clear() {
var canvas = document.getElementById("canvasWhite");
canvas.width = canvas.width;
}
</script>
<button class="btn btn-bnw" onclick="javascript:canvas_genRandomBNW();" type="button">Add Black&amp;White Noise!</button>
<button class="btn btn-color" onclick="javascript:window.canvas_genRandomCOLOR();" type="button">Add Color Noise!</button>
<button class="btn btn-getImage" onclick="javascript:window.canvas_getImage();" type="button">Open Image In New Tab!</button>
<button class="btn btn-clear" onclick="javascript:window.canvas_clear();" type="button">Clear</button></body>
</html>
```

here are some fun variations to base-formula and graphic-outputs,
which shows some white (empty) areas due to log's nature,
same goes for the color randomness, which seems to create a lovely-distribution maps :]

• `Math.log2(1+1/number) / Math.log2(number);`
• `Math.log2(number);`
• `Math.log2(number) + Math.log2(number);`
• `Math.log10(number) * Math.log10(number);`
• `Math.log10(number) % Math.log2(number);`

try the next version yourself (also, you can right click it to see the source-code, or paste it in bin.eladkarako.com for quick variations fun :] )

# True Random

There are two principal methods used to generate random numbers. One measures some physical phenomenon that is expected to be random and then compensates for possible biases in the measurement process. The other uses computational algorithms that produce long sequences of apparently random results, which are in fact completely determined by a shorter initial value, known as a seed or key. The latter type are often called pseudo-random number generators.

Pseudo-random implementations, like LCG (linear congruential generator), usually uses a seed using a couple of runs with with a slightly different values of the multiplier coefficient (more on LCG).

True randomness can achieved from the sound a Zener diode caused by its avalanche breakdown, another way is sampling statics or a “white noise” this can be done using any simple receiver.

is doing just that, offering a free, online generator.

generate integer using the HTTP service.
Generating 1 random number [1 to 100, base 10] is easy!
http://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new
Watch

The downsize is active connection to the internet and a small delay, even thou the output does not need parsing.

quick&dirty wrapping:

```Private Function trueRandom(ByVal num As Long, ByVal min As Long, ByVal max As Long) As Long()
On Error Resume Next
With Inet1
.Document = "/integers/?num=" & num & "&min=" & min & "&max=" & max & "&col=1&base=10&format=plain&rnd=new"
.RemoteHost = "www.random.org"
.URL = "http://www.random.org/integers/?num=" & num & "&min=" & min & "&max=" & max & "&col=1&base=10&format=plain&rnd=new"
End With
Dim s as String
s=Inet1.OpenURL
'Here a Small Delay...
trueRandom=CInt(Trim\$(s))
End Function
```