If that happens, it's a bug in the player. From the docs:

"Returns a pseudo-random number n, where 0 <= n < 1. "

So, the biggest number random returns can approximate 1, but should never be
1.

What I got wrong in my original answer was that multiplying by 2 and then
rounding introduces a bias towards  1 (and then if you substract 1, the bias
is towards 0).

Think about it this way:

You've got a number between 0 and 1.99999 when you do Math.random *  2. That
is, a number that can get very close to 2, but never be actually 2.

If you round it you'll get:

0 for 0...0.49
1 for 0.5...1.49
2 for 1.5...19

The actual numbers might not be exact as I'm not sure what's the boundary
for rounding up or down; I'm also considering only two decimals for
simplicity.

But anyway, the distribution is obviously not even. There's about a 0.25
chance of getting 0, the same chance of getting 2, but the double, 0.5, of
getting 1.

However, if you multiply by 3 and floor the result (or coerce it to int for
that matter), you get rid of the bias:

Math.random * 3 will give a number in the range 0...2.99

So, if you get rid of the decimal part, you have:

0 for 0...0.99
1 for 1...1.99
2 for 2...2.99

Which gives a result that's clearly more evenly distributed than the first
approach.


2010/5/9 Steven Sacks <[email protected]>

> In the exception that Math.random() returns 1, in which case you would get
> 2.
>
> I don't use Math.random(), though, I use the Parker-Miller PRNG.
>
>
>
>
> On 5/9/2010 5:01 PM, Juan Pablo Califano wrote:
>
>> PS 2: I think the correct way to write the function that returns a number
>> in
>> the range -1 / 1 is:
>>
>> Math.floor(Math.random * 3) - 1
>>
>> In this case, you could indeed use int() instead of a static Math method,
>> so
>> I guess I was wrong about your function needing a Math.round call.
>>
> _______________________________________________
> Flashcoders mailing list
> [email protected]
> http://chattyfig.figleaf.com/mailman/listinfo/flashcoders
>
_______________________________________________
Flashcoders mailing list
[email protected]
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

Reply via email to