views:

858

answers:

3

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

+30  A: 

Because the multiplication overflows 32 bit integers. In 64 bits it's okay:

public class Test
{
    public static void main(String[] args)
    {
        int intProduct = 24 * 60 * 60 * 1000 * 1000;
        long longProduct = 24L * 60 * 60 * 1000 * 1000;
        System.out.println(intProduct); // Prints 500654080
        System.out.println(longProduct); // Prints 86400000000
   }
}

Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.

Jon Skeet
What does 1000 days * 1000 mean anyway?
Joel Coehoorn
Those must be them new "metric years" they're always talkin' about.
Don Branson
1000 days * 1000 would be 1,000,000 days. There's nothing mysterious about that. Now, 1000 inches x 1000 inches is 1,000,000 square inches, so presumably 1000 days x 1000 days would be 1,000,000 square days. But I'm not exactly sure what a "square day" is. Perhaps that's a unit of measure that time travellers use when dealing in pan-dimensional space.
Jay
Days ? 24*60'60*1000*1000 is the nr of microseconds in a day. :)
nos
i think it would depend on units, whether microseconds in a day or days in metric year?
understack
+17  A: 

You need to start with 24L * 60 * ... because the int overflows.

Your question BTW is a copy/paste of Puzzle 3: Long Division from Java Puzzlers ;)

cherouvim
+1 for long constant to force long instead of int.
Thorbjørn Ravn Andersen
+2  A: 

If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.

Thom Smith
re-ordering the numbers will not avoid the overflow
cherouvim
@cherouvim, but reordering the operations could.
Nosredna
I believe Thom is talking about reordering the multiplication so you do something like this instead: ((24 * 60)/(24 * 60)) * ((1000 * 1000)/(1000*1000))
DeadHead
yes that is correct.
cherouvim
Fixed size integers are integers modulo a number (a residue class ring), so operations other than division have all the usual good properties (associative, commutative, distributive, ...). This doesn't hold for floating point, though.
starblue