Article View: borland.public.jbuilder.java.language
Article #16319Re: 0.3-0.2=0.999999999998?
From: Rene
Date: Wed, 10 Mar 1999 00:00
Date: Wed, 10 Mar 1999 00:00
43 lines
2446 bytes
2446 bytes
On Tue, 09 Mar 1999 19:37:11 GMT, Rick Stabile
<stabilpa@my-dejanews.com> wrote:
>Am I not getting something here? I tried this in PowerJ and my result was
>0.1. In any case, I could understand a result of 0.0999999999998, or even
>0.999999999998E-01 -- it's floating point arithmetic and this sort of result
>is to be expected. But did the author of this post simply make a typo that no
>one else mentioned, or is his result really an order of magnitude too large
The output of JDK 1.1.7 on Windows is
0.09999999999999998
which is problably correct in terms of IEEE floating point
specification. You get the same result with format %0.17f in C.
However, using %g rounds to 0.1 as expected.
The result is surprising, because 0.1 does not seem to equal 0.3-0.2,
which can be checked by 0.3-0.2==0.1 (resulting in false). This is
again correct with proper rounding in base 2.
To learn the core of the problem, try
public class Test
{ static public void main (String args[])
{ double x=2;
for (int i=0; i<100; i++)
{ System.out.println(i+" "+(1.0-x)+" "+((1.0-x)==1.0));
x=x/2;
}
}
}
You will see that Java uses a 54 bit binary arithmetic. The output
routine will not round 0.9999999999999999 to 1.0, which needs to be
considered. If you think about it, we need to represent 1-2^(-53) in
decimal. This is .999999999999999888977697537484 correct to 29 places.
There are 15 9ers. Wether or not this should print as 1.0 is somewhat
a matter of convention. In my opinion, it should and Java is wrong
here (as well as C), because the closest representation is 1.0.
The other question is how to get a decent output of double numbers in
Java. This can be done with the NumberFormatters of JDK 1.1.
Technical Details
Message-ID:
<36e65000.9658117@news.uni-erlangen.de>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<7blg56$2pl$1@zonnetje.NL.net> <7c3t96$tj8$1@nnrp1.dejanews.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 10a146,3b89176b465afef X-Google-Attributes: gid10a146,public X-Google-Thread: f5d71,3b89176b465afef X-Google-Attributes: gidf5d71,public X-Google-Thread: f74b3,3b89176b465afef X-Google-Attributes: gidf74b3,public From: grothm.remove.this@no.spam.ku-eichstaett.de (Rene) Subject: Re: 0.3-0.2=0.999999999998? Date: 1999/03/10 Message-ID: <36e65000.9658117@news.uni-erlangen.de> X-Deja-AN: 453352917 References: <7blg56$2pl$1@zonnetje.NL.net> <7c3t96$tj8$1@nnrp1.dejanews.com> Organization: Regionales Rechenzentrum Erlangen, Germany Newsgroups: borland.public.jbuilder.java.language,comp.lang.java,comp.lang.java.programmer