Author: Daniel Clausen
Date: 07:35:07 09/09/02
Go up one level in this thread
On September 09, 2002 at 10:04:12, Ed Panek wrote:
>long x;
>double y;
>
>y = 2.01;
>x = (long)(y * 1000);
>
>
>guess what x equals? ...
>
>No, not 2010, but 2009 !!!!!!!!!!!!!!!
>
>Ed
CM9k doesn't support your graphics card.. umm.. wrong thread!
Ok, serious now: That's not a Java oddity but a floating-point oddity. (and
happens in C and other languages as well) Floating-point numbers often can't be
represented exactly in a computer.
Integer:
101010(binary) means 1*2^5 + 0*2^4 + 1*2^3 + 0*2^2 + 1*2^1 + 0*x^0 = 42
1 0 1 0 1 0
Similarly computer represent numbers between 0 and 1, but:
the 1st digit has weight 0.5
the 2nd digit has weight 0.25
then 0.125, etc.. you get the idea
In your example, the number "2.01" doesn't have an exact representation in a
computer. (at least I don't think so - correct me when I'm wrong :) In fact, the
internal representation is just a tiny bit below 2.01. Now if you multiply that
by 1000, it will be just a tad below 2010, and if you convert that to an integer
(which does not round, it cuts off the rest) it yields the result 2009.
Hope this helps.
Sargon
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.