What range of Numbers? Seriously, I got headache trying to figure it out -_-
public function gerRandom(i:uint):uint {
return Math.round(Math.random()*i);
}
Whole numbers from 0
to i
including? I need these.
开发者_StackOverflow中文版A kind of a noob question, but whatever :D
Math.random() will create a number from 0 to 1 (not including 1). So your code would create a value between 0 and i, with less chance to get 0 and i compared to the other values in the range (it will only round down to 0 on a 0.5 or less, and up to 'i' on a 'i'-0.5 or more).
A better way is to use
public function getRandom(from:uint, to:uint):uint {
return Math.floor(Math.random()*(to-from+1))+from;
}
(iirc).
Will return whole number from 0
to i
, both inclusive, but not with equal probability. You'll get 0
if Math.random()*i
is the interval [0, 0.5)
, but you get 1
if it's in [0.5, 1.5]
.
Use Math.floor(Math.random() * (i + 1))
instead.
An integer between 0 and i (both included) :)
Math.random()
return a value between 0 and 1Math.random*i
return a number between 0 and iMath.round(Math.random()*i)
returns an integer between 0 and i.
精彩评论