Live data from Hacker News

A common bug in published code

google.com

11–20 of 79 posts

Re: A common bug in published code

#14
post #4
post #3

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…

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

[deleted]

Re: A common bug in published code

#20

Apparently, 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?

Slight difference here. There are actually two types of errors in the Java code:

1. int foo = (int) Math.random() * some_max_value;

The error here is assuming that the multiplication takes place before the truncation. This isn't happening in the Python code because int(expression to truncate) is unambiguous. (+1 to Python here for making it hard to shoot yourself in the foot).

2. int foo = (int) Math.random();

The error here is assuming that Math.random returns something outside [0.0, 1.0). This is the error that all five of the Python examples are showing. (Boo to Python AND Java programmers.)

Post reply on HN