5 ms·
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
by jimm 15y ago
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.
- jerfelix 15y agoThey are not in error if you are trying to get a 0. This is yet another good technique for obfuscated code.
- nbpoole 15y agoIndeed. Take a look at http://www.google.com/codesearch/p?hl=en#TXS-ndgbCls/trunk/junit/org/homeunix/thecave/buddi/test/model/TransactionTest.java&q=%5C(int%5C)%5Cs*Math%5C.random%5C(%5C)&sa=N&cd=20&ct=rc&l=56 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.
- ubernostrum 15y agoA 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.
- spullara 15y agoThis 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.
- ubernostrum 15y agoThe 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.
- masklinn 15y ago> 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. For the code to work, you need `(int) (Math.random() * a)`: http://www.google.com/codesearch?q=\(int\)\s*\(\s*Math\.random\(\) http://www.google.com/codesearch?q=\(int\)\s*\(\s*Math\.rand...