The first few examples are fine. It's the unscaled ones later on, like "longarr[i] = (int) Math.random();" and especially "[Math.abs((int) Math.random()) % 3];" where the authors didn't notice that random() "returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
The cast has higher precedence than multiplication, so the scaling doesn't help at all, unless you use parenthesis to force the right order of evaluation.
They are all in error. "(int)Math.random()" always returns 0 because Math.random() returns [0.0, 1.0) (i.e., does not include 1). Casting that return value to a int will always return 0.
Indeed. Take a look at http://www.google.com/codesearch/p?hl=en#TXS-ndgbCls/trunk/j... for instance: if you weren't looking for an incorrect cast, it would be very hard to notice. Two out of three casts are correct: only one is missing the parentheses.
A lot of the results I'm seeing in the search have more problems with order of operations -- so long as you multiply the random() result by a good-sized constant before you cast to int, it actually does what it's "supposed" to do.
This is the point of the post. There are no examples that aren't casting Math.random() to an int before doing anything with it thus using a pretty expensive way to represent 0.
The comment I was replying to was simply saying that casting the return value of Math.random() will be 0. Which is true, but is not the issue -- order of operations (for people who think the multiplication happens before the cast) is the issue.
> so long as you multiply the random() result by a good-sized constant before you cast to int, it actually does what it's "supposed" to do.
Yeah but since cast binds tighter than multiplication, any code following the pattern `(int) Math.random() * a` is broken and generates 0 every single time.
Here's another extreme example: (int) Math.random() / Integer.MAX_VALUE % (maxScoreCount + 1);
I eyeballed that about 5% of the calls are in error.