Posts Tagged ‘exponent’

Weighted Random Number

Monday, April 26th, 2010

If you are new to JavaScript, the method to get a random number may be difficult to grasp. The built-in function Math.random() does not accept any arguments, and it returns a decimal between 0 (inclusive) and 1 (exclusive). Most often, we want a whole number, maybe to be used for accessing a random element in an array. Consequently, random generators usually have to be custom coded. But what if we want to get a more weighted distribution of random numbers? Say of a random number between 1-5 we want 1 to show more often than 5? Even if you are not new to JavaScript, determining the math to add a weight to a random result can be quite tricky.

(more…)