CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2000
    Posts
    13

    Angry question: double C++

    why is: dA(=200.9) - sSub(=100.3) != dB(=100.6)

    double dA=200.9, dSub=100.3;
    double dB=100.6;

    if( dA-dSub == dB)
    int x=1;
    else
    int Y=1;

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    That is because 200.9 can't be represented exactly on a double. dA will be 200.90000000000001. You can guess the rest...

    The morale is: never use == on floating point results as condition for branches or loops...
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  3. #3
    Join Date
    Feb 2000
    Posts
    13
    could you explain to me in details why 200.9 can't be represented exactly on a double

  4. #4
    Join Date
    Sep 2002
    Location
    14° 39'19.65"N / 121° 1'44.34"E
    Posts
    9,815
    Quote Originally Posted by Christian Hofner
    could you explain to me in details why 200.9 can't be represented exactly on a double
    This paper explains it pretty well...

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449
    Quote Originally Posted by Christian Hofner
    could you explain to me in details why 200.9 can't be represented exactly on a double
    Not to get into floating point representations such as IEEE, but the simplest answer is for you to try and convert 0.9 to binary. You will see that when it is converted, you get a repeating, non-terminating binary floating point number, while 0.9 is a terminating, non-repeating, decimal number.

    0.9 (decimal) = 0.11100110110110110....110... (binary)

    This is basically the same reason why "1 / 3 * 3" is 0.9999999 on some of the older hand calculators, when mathematically it should be 1.0000000 in that "1/3" cannot be represented exactly as a floating point number in binary. Unless the decimal floating point number is a sum of inverse powers of 2 (for example 1/2, 1/4, 1/8, 1/16, etc.) then the decimal number cannot be represented exactly in binary.

    Of course, there are processors that handle a lot of these "inexact" issues, but they are not 100% perfect, as you can see from your program. It still boils down to the fact that decimal values cannot be represented exactly as binary values (not counting the case I mentioned above with the inverse powers of 2).

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured