
A common bug in published code - shawndumas
http://www.google.com/codesearch?lr=&q=\(int\)\s*Math\.random\(\)
======
samps
Someone should write a tool that scrapes these results and automatically files
bugs at the associated bug trackers for open-source projects.

~~~
bnewbold
I've been thinking of doing something and i'm looking for people to work with!
Notes here: <http://memeschemes.com/code_search/>

~~~
mbenjaminsmith
A bug in _that_ program would certainly be wonderful. Have fun when it files a
few million unnecessary bug reports while you're sleeping.

~~~
mail2345
Have it require approval for each bug report. While it isn't as fast as a
fully automatic bug finding system, it is faster than a manual find and file.
Plus it takes care of those situations where it was intended(poor coding, but
it works).

------
rmccue
For those who haven't picked up the error: Math.random() returns a value
between 0 and 1, and the typecasting floors the value.

------
Adrock
See the previous HN discussion: <http://news.ycombinator.com/item?id=960886>

~~~
__mark
Oh, so it always rounds down to zero, that's pretty bad. Casting it to a
double would help right?

~~~
Thasc
Instead of

int runs = (int) Math.random() * 1000000;

You'd do

int runs = (int) (Math.random() * 1000000);

------
ChuckMcM
One would hope at some point a tool would warn you about this since clearly it
could optimize (int) Math.random() to just 0.

[queue debate about tools that hold your hands vs understanding what you are
actually writing]

I wonder if they did the search for if (x = y) bug pre-gcc-4.x-warn what sort
of numbers they would get.

~~~
derleth
> queue

Speaking of common bugs...

(The word you're looking for is 'cue'.)

~~~
nolanw
Were you actually confused, or are you just picking nits? If the latter, then
it's not really a bug is it.

~~~
kwantam
Actually, nits _are_ bugs. They just haven't hatched yet.

[1] <http://en.wikipedia.org/wiki/Louse>

------
ghewgill
Last year I found several instances of the printf format "200%d" when dealing
with years. Some still exist:
[http://hewgill.com/journal/entries/548-y2010-bugs-found-
via-...](http://hewgill.com/journal/entries/548-y2010-bugs-found-via-google-
code-search)

~~~
dgallagher
I think that's called job security in some circles. ;)

------
baltcode
Apparently, python only has 5 instances of the corresponding error:
[http://www.google.com/codesearch?hl=en&lr=&q=\s%2Bin...](http://www.google.com/codesearch?hl=en&lr=&q=\\s%2Bint\\s*\\\(\\s*random\\.random\\\(\\\)\\s*\\\)&sbtn=Search)

Python-Java flame-war, anyone?

~~~
myelin
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.)

~~~
ZoFreX
Third error: This is not the correct way to randomly pick a number in a set
range. The proper way is actually quite complicated. Imagine you do (int)
(Math.random() * 10), this could give you numbers from 0 to 10. However, you
only get 0 if Math.random() * 10 is less than 0.5, but you get 1 if the value
is between 0.5 and 1.5. You are half as likely to see a zero!

I can't speak for Python, but in Java it's quite simple to do it right;
Random#nextInt(int) "Returns a pseudorandom, uniformly distributed int value
between 0 (inclusive) and the specified value (exclusive)" (also consider
using SecureRandom).

~~~
calpaterson
I actually struggle to understand why people even use Math.random() when the
Random class exists.

~~~
nostrademons
Don't need an import for Math.random(). Random is in java.util, while Math is
in java.lang.

------
nicetryguy
im floored

~~~
mattdeboard
Yeah, I nearly hit the ceiling myself.

~~~
richardw
Random ints between 0 and 1 offer a pretty limited range of jokes, I guess.

<http://en.m.wikipedia.org/wiki/Range_(computer_science)> Edit: added range
def because of downvotes. Sigh

------
ilcavero
the main cause here is that randomness is hard to test so that code was just
assumed to be correct. With randomness you can never be sure,
<http://www.random.org/analysis/>

~~~
klodolph
Yes, but... (int)Math.random() always returns zero. A little suspicious.

~~~
polynomial
You can never be sure the next one won't be a 1!

------
ghempton
Majority of these results are examples and test cases which is probably why
the bugs have not manifested themselves.

------
merloen
Any other examples of bugs that you can search for?

------
ignifero
A-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*...](http://www.google.com/codesearch?hl=en&lr=&q=if%5Cs*%5C%28%5Cs*%5Cw%2B%5Cs*%3D%5Cs*%5Cd%2B%5Cs*%5C%29+file%3A^.*%5C.c%24&sbtn=Search)

vs

[http://www.google.com/codesearch?hl=en&lr=&q=if%5Cs*...](http://www.google.com/codesearch?hl=en&lr=&q=if%5Cs*%5C%28%5Cs*%5Cw%2B%5Cs*%3D%5Cs*%5Cd%2B%5Cs*%5C%29+file%3A^.*%5C.cpp%24&sbtn=Search)

~~~
benburleson
That's why I write comparisons like

if (CONSTANT == variable)

~~~
Splines
I know it's safer, but personally I find it harder to read. Especially if the
constant is a #define or enum and is similar in format to the variable in
question.

~~~
nostrademons
I personally like Yoda Conditions, but a few coworkers have pointed out that
any linter worth its salt will catch an = inside a conditional, so this
doesn't actually gain much in safety. I've stopped using them because there a
large number of coworkers find them confusing.

------
dalke
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 5% of the calls are in error.

~~~
nbpoole
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

~~~
electrum
It is random! <http://xkcd.com/221/>

