why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
views:
858answers:
3
+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
2009-08-19 17:16:41
What does 1000 days * 1000 mean anyway?
Joel Coehoorn
2009-08-19 17:18:15
Those must be them new "metric years" they're always talkin' about.
Don Branson
2009-08-19 17:22:40
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
2009-08-19 18:22:33
Days ? 24*60'60*1000*1000 is the nr of microseconds in a day. :)
nos
2009-08-19 18:49:50
i think it would depend on units, whether microseconds in a day or days in metric year?
understack
2010-01-29 19:17:25
+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
2009-08-19 17:17:01
+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
2009-08-19 17:18:18
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
2009-08-19 17:34:20
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
2009-08-19 20:22:15