...

View Full Version : Randomly referencing array index



Mr J
05-29-2004, 12:32 AM
When randomly referencing an arrays index which is the best method to use.

Math.round(Math.random()*5)

or

Math.floor(Math.random()*5)

with an array set out as follows

array_name=new Array()

array_name[0]=""
array_name[1]=""
array_name[2]=""
array_name[3]=""
array_name[4]=""

Vladdy
05-29-2004, 01:07 AM
Array.prototype.getRandom = function()
{ return this[Math.floor(Math.random()*this.length)];
}

liorean
05-29-2004, 01:18 AM
Math.round gives half probability to either of the top/bottom choices. Math.floor and Math.ceil are better, since the probability of a return value ofexactly 1 and 0 from Math.random, respectively, is so infinitely small ((2^64 - 2^54)^-1, if you want to know) that it's almost impossible. However, multiplying with a large number and then calculating the modulo of the array length would eliminate even that small chance.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum