Page 77 - JavaScript
P. 77
Warning: Bitwise operators such as & and | are not the same as the logical operators && (and)
and || (or). They will provide incorrect results if used as logical operators. The ^ operator is not
b
the power operator (a ).
Get Random Between Two Numbers
Returns a random integer between min and max:
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Examples:
// randomBetween(0, 10);
Math.floor(Math.random() * 11);
// randomBetween(1, 10);
Math.floor(Math.random() * 10) + 1;
// randomBetween(5, 20);
Math.floor(Math.random() * 16) + 5;
// randomBetween(-10, -2);
Math.floor(Math.random() * 9) - 10;
Random with gaussian distribution
The Math.random() function should give random numbers that have a standard deviation
approaching 0. When picking from a deck of card, or simulating a dice roll this is what we want.
But in most situations this is unrealistic. In the real world the randomness tends to gather around
an common normal value. If plotted on a graph you get the classical bell curve or gaussian
distribution.
To do this with the Math.random() function is relatively simple.
var randNum = (Math.random() + Math.random()) / 2;
var randNum = (Math.random() + Math.random() + Math.random()) / 3;
var randNum = (Math.random() + Math.random() + Math.random() + Math.random()) / 4;
Adding a random value to the last increases the variance of the random numbers. Dividing by the
number of times you add normalises the result to a range of 0–1
As adding more than a few randoms is messy a simple function will allow you to select a variance
you want.
// v is the number of times random is summed and should be over >= 1
// return a random number between 0-1 exclusive
function randomG(v){
var r = 0;
https://riptutorial.com/ 34

