Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

Strange results when adding two double primitives - Java 1.5.0_04

Thread view: 
Chris Brat - 11 Oct 2006 15:00 GMT
Hi,

I've found this little oddity in the application I'm working on where
the result of adding two double primitives gives a result that either
has an extra 0.0000000000000002 or it is 0.0000000000000001 less than
the expected result.

This sample app illustrates it.

Does anyone know why this happens ?

Thanks
Chris

public class A {

   public static void main (String[] args){
       double a = 67.41;
       double b = 51.85;
       double result = a + b;

       // I get 119.25999999999999
       System.out.println(result);

       a = 1.01;
       b = 2.02;
       result = a + b;

       // I get 3.0300000000000002
       System.out.println(result);

       a = 1.100;
       b = 2.103;

       result = a + b;
       // 3.2030000000000003
       System.out.println(result);
   }
}
Mike Beaty - 11 Oct 2006 15:07 GMT
Chris

The problem is that with float and double some numbers cannot be
exactly represented in binary form, thus losing some precision.  See #4
on this page:  http://www.mindprod.com/jgloss/floatingpoint.html

-Mike
> Hi,
>
[quoted text clipped - 35 lines]
>     }
> }
Chris Brat - 11 Oct 2006 15:14 GMT
Hi,

Thanks for the response - just came across explaination and some rants
at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4497156

Chris
Mike Beaty - 11 Oct 2006 15:49 GMT
I recently ran into this when doing an 80%/20% split on a number,
storing it and then trying to put those two parts back together.  It's
crazy that the Java language can't handle this and provide the expected
results.  They are saying it's not a defect it's a feature...I wish I
could use that one.

-Mike

> Hi,
>
> Thanks for the response - just came across explaination and some rants
> at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4497156
>
> Chris
opalpa opalpa@gmail.com http://opalpa.info - 11 Oct 2006 16:09 GMT
> I recently ran into this when doing an 80%/20% split on a number,
> storing it and then trying to put those two parts back together.  It's
> crazy that the Java language can't handle this and provide the expected
> results.  They are saying it's not a defect it's a feature...I wish I
> could use that one.

How numbers are stored in computer memory is introductory programming
material.   There is wide consensus on storing real numbers in finite
sequences of bits.   The Java language handles the situation according
to this cosmopolitan consensus.

The Java language is ready to accomodate your needs in various ways.  I
suspect a little programming education will go a long ways for you.

All the best,
opalpa
opalpa@gmail.com
http://opalpa.info/
Mike Beaty - 11 Oct 2006 16:39 GMT
On Oct 11, 11:09 am, "opalpa opa...@gmail.com http://opalpa.info"
<opa...@gmail.com> wrote:

> The Java language is ready to accomodate your needs in various ways.  I
> suspect a little programming education will go a long ways for you.

Mike Beaty --> MBA, BBA, SCJP, SCWCD

I suspect I was just stating an opinion that the Java language should
handle this mathematical inaccuracy, even though it is a commonly
accepted defect.
Greg R. Broderick - 12 Oct 2006 22:10 GMT
"Mike Beaty" <beatymj@gmail.com> wrote in news:1160581168.768710.42120
@m7g2000cwm.googlegroups.com:

> the Java language should handle this mathematical inaccuracy, even
> though it is a commonly accepted defect.

Feel free to design and submit a Java Community Process (c.f.
http://www.jcp.org/) Java Specification Request to remedy this 'defect'.

Oh, and while you're at it, you might want to submit the same design
proposal to Intel, AMD and other microprocessor designers to remedy the
same 'defect' in their floating point hardware.

Regards
GRB
Patricia Shanahan - 13 Oct 2006 00:19 GMT
> "Mike Beaty" <beatymj@gmail.com> wrote in news:1160581168.768710.42120
> @m7g2000cwm.googlegroups.com:
[quoted text clipped - 11 lines]
> Regards
> GRB

I want to see the proposal for ensuring exact results for square root,
sine, cosine, logarithm etc.

Patricia
John W. Kennedy - 13 Oct 2006 03:11 GMT
> "Mike Beaty" <beatymj@gmail.com> wrote in news:1160581168.768710.42120
> @m7g2000cwm.googlegroups.com:
[quoted text clipped - 8 lines]
> proposal to Intel, AMD and other microprocessor designers to remedy the
> same 'defect' in their floating point hardware.

Don't forget telling IBM about this same "defect" in every mainframe
they made in the last 40 years.

Signature

John W. Kennedy
"The blind rulers of Logres
Nourished the land on a fallacy of rational virtue."
  -- Charles Williams.  "Taliessin through Logres: Prelude"

Thomas Weidenfeller - 11 Oct 2006 16:30 GMT
> I recently ran into this when doing an 80%/20% split on a number,
> storing it and then trying to put those two parts back together.  It's
> crazy that the Java language can't handle this and provide the expected
> results.  They are saying it's not a defect it's a feature...I wish I
> could use that one.

You have done a serious design mistake if you design software using
float or double and expecting unlimited accuracy. This is not something
new. It wasn't just discovered yesterday. It dates back to the dawn of
computers. It happens with every language which uses the typical
fixed-length mantissa + exponent representation internally.

I looked at the rants in the bug report. Boy, don't these kids learn
anything in school any more?

And I am not talking about knowing the precise internal format of IEEE
754. I am talking about basic things like knowing that 0.1 in base ten
is a periodic number in base two. So it can hardly be accurately
represented in a fixed amount of bits. Or just applying some basic
logic. It is logical that not every existing real (in the mathematical
sense) number can be represented with a fixed amount of bits. Simply
because there is an infinite amount of real numbers.

Do they really not teach these basics any more?

Shocking, shocking ...

/Thomas
Signature

The comp.lang.java.gui FAQ:
http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq

Mike Beaty - 11 Oct 2006 16:44 GMT
I f*cking forgot okay...suck my fukkin a$$.

I try and try, but I hate these friggin' newsgroups.  All you do is try
to help somebody and friggin' arrogant a-holes like you jump all over
my case, trying to act like you're all high and mighty.  You know,
being a wanna-be know-it-all doesn't make people respect you more.

Newsgroups suck...you can all kiss my a$$!!!!!

On Oct 11, 11:30 am, Thomas Weidenfeller <nob...@ericsson.invalid>
wrote:
> > I recently ran into this when doing an 80%/20% split on a number,
> > storing it and then trying to put those two parts back together.  It's
[quoted text clipped - 24 lines]
> --
> The comp.lang.java.gui FAQ:http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/ftp://ftp.cs.
uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
Oliver Wong - 11 Oct 2006 17:23 GMT
> I looked at the rants in the bug report. Boy, don't these kids learn
> anything in school any more?

[...]

> Do they really not teach these basics any more?
>
> Shocking, shocking ...

   Indeed. It is *so* unbelievable to me, in fact, that I suspect it's a
form of trolling, rather than genuinely misguided programmers.

   - Oliver
Chris Uppal - 11 Oct 2006 17:45 GMT
>     Indeed. It is *so* unbelievable to me, in fact, that I suspect it's a
> form of trolling, rather than genuinely misguided programmers.

Hmm, yes.  Looking at, for instance, this comment on the "bug" report:

   It is ridicule and stupid.
   0.33 can be store like a float or a double.
   I think the IEEE 754 rounding implementation is bugged.
   It's scandalous! Think about financial or scientific
   application !

I would say that whoever posted that was indulging a somewhat warped[*] sense
of humour.

   -- chris

[*] still pretty funny, though.
Jeffrey Schwab - 11 Oct 2006 17:58 GMT
>>     Indeed. It is *so* unbelievable to me, in fact, that I suspect it's a
>> form of trolling, rather than genuinely misguided programmers.
[quoted text clipped - 13 lines]
>
> [*] still pretty funny, though.

It's annoying that support folks and usenetters have wasted time on
this, but that has got to be the funniest bug report I've ever read.

"Pffff ... don't tell me that's normal, and it's not a bug ... What is
floating-point arithmetic advantage if it gives false results ..?

"I'm looking for a SOLUTION, not explanation .. And I don't want to hear
about any "BigDecimal" class, my application took 1000 man days to
develop, imagine how long it will be to adapt all floating points
operations. . . "
Andy Dingley - 11 Oct 2006 23:15 GMT
>     Indeed. It is *so* unbelievable to me, in fact, that I suspect it's a
> form of trolling, rather than genuinely misguided programmers.

Never put down to conspiracy that which can be explained by stupidity.
- especially not on Usenet!

Remember the sqrt(-1) bug that was in Excel a few years ago ?
When reporting this to an Excel-loving manager at a major bank in the
Square Mile, his response was "So? Just how inaccurate is it?"
Mark Thornton - 13 Oct 2006 19:22 GMT
> And I am not talking about knowing the precise internal format of IEEE
> 754. I am talking about basic things like knowing that 0.1 in base ten
[quoted text clipped - 5 lines]
>
> Do they really not teach these basics any more?

I'm sure they are still taught, but many students probably don't take
the units which contain this information. After all quite a lot of
programming can be done without using floating point at all. I guess
what is missing is they haven't been taught that use of floating point
without having done relevant units is an exercise fraught with
unexpected experiences.

Mark Thornton
Patricia Shanahan - 11 Oct 2006 17:16 GMT
> Hi,
>
> I've found this little oddity in the application I'm working on where
> the result of adding two double primitives gives a result that either
> has an extra 0.0000000000000002 or it is 0.0000000000000001 less than
> the expected result.

No matter what radix is used, there will be some rationals that cannot
be represented exactly as an integer scaled by a power of the radix,
leading to rounding error.

For many applications, the radix does not matter to the application. For
example, some applications do calculations whose infinitely precise
result is irrational, and, short of symbolic math systems, rounding
error is inevitable. Two is the best radix for very compact, high
performance hardware implementation.

However, it is also a reality that, for some applications, those numbers
that are exactly representable with radix 10 are particularly important.
That is why Java provides the class java.math.BigDecimal. It gives up
some of the efficiency of double, but gains exact representation of any
decimal fraction. Here is your program, converted to use BigDecimal:

import java.math.BigDecimal;

public class BigDecimalTest {

  public static void main(String[] args) {
//    double a = 67.41;
    BigDecimal a = new BigDecimal("67.41");
//    double b = 51.85;
    BigDecimal b = new BigDecimal("51.85");
//    double result = a + b;
    BigDecimal result = a.add(b);
//
//    // I get 119.25999999999999
    System.out.println(result);
//
//
//
//    a = 1.01;
    a = new BigDecimal("1.01");
//    b = 2.02;
    b = new BigDecimal("2.02");
//    result = a + b;
    result = a.add(b);
//
//    // I get 3.0300000000000002
    System.out.println(result);
//
//    a = 1.100;
    a = new BigDecimal("1.100");
//    b = 2.103;
    b = new BigDecimal("2.103");
//
//    result = a + b;
    result = a.add(b);
//    // 3.2030000000000003
    System.out.println(result);
  }

}

Output:

119.26
3.03
3.203

Note that, in this particular case, you could have got the ideal output
by just using DecimalFormat or System.out.printf to print the doubles
rounded to a reasonable precision. However, with more significant digits
in the inputs, or a lot more steps in the calculations, the rounding
error could affect digits that matter.

Patricia
adwords@pulpjava.com - 13 Oct 2006 14:20 GMT
Precision on extremely long floats, and some calculations, end up with
strange results. This isn't uncommon. Classes such as BigDecimal can
help avoid some of these issues.

-Cameron McKenzie www.pulpjava.com www.examscam.com www.scja.com

Check out my new SCJA certification guides and mock exam questions at
www.scja.com

> Hi,
>
[quoted text clipped - 35 lines]
>     }
> }


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.