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." Here's another extreme example: (int) Math.random() / Integer.MAX_VALUE % (maxScoreCount + 1); I eyeballed that about…
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.
A common bug in published code
21–30 of 79 posts
Re: A common bug in published code
#22See the previous HN discussion: http://news.ycombinator.com/item?id=960886
Re: A common bug in published code
#23Earlier quoted context omitted.
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.
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.
Re: A common bug in published code
#24Someone should write a tool that scrapes these results and automatically files bugs at the associated bug trackers for open-source projects.
Re: A common bug in published code
#25Apparently, python only has 5 instances of the corresponding error: http://www.google.com/codesearch?hl=en&lr=&q=\s%2Bin... Python-Java flame-war, anyone?
a = random.randrange(10000)Re: A common bug in published code
#26Re: A common bug in published code
#27im floored
Re: A common bug in published code
#28A-mazing Also, notice the difference in number of results between C and C++ below: http://www.google.com/codesearch?hl=en&lr=&q=if%5Cs*... vs http://www.google.com/codesearch?hl=en&lr=&q=if%5Cs*...
if (CONSTANT == variable)
Re: A common bug in published code
#29im floored
Re: A common bug in published code
#30The 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." Here's another extreme example: (int) Math.random() / Integer.MAX_VALUE % (maxScoreCount + 1); I eyeballed that about…
That's not true. Try running the following code: public class Test { public static void main(String[] args) { System.out.println("Test: " + (int)Math.random() * 100); System.out.println("Test: " + (int)(Math.random() * 100)); } } My results, from repeated tests: java Test Test: 0 Test: 59 java Test Test: 0 Test: 18 java Test Test: 0 Test: 72 java Test Test: 0 Test: 11