tags:

views:

59

answers:

4

I can not get to make this comparison in this simple code error .. what kind I'm making and what is the reason? ...

#include <stdio.h>

int main()
{
    double a = 0.0;
    double b = 1.0;
    double c = 0.1;

    while( a != b )
        a=a+c;

    printf("Suma hasta 1 completada\n");
}

tnx for the answers...

+3  A: 

Make it while ( a <= b )

Operations with double (and the datatypes itself) have problems with precision. So, avoid using double == double or double != double expressions. Rearrange them with < or >. Probably after the 10th iteration c is 1.00000 .. 001, instead of just 1. This is due mainly to the internal representation of double types.

anthares
I somewhere read that some languages such as java are hiding the precision issue. Is that true ?
Niklaos
What do you mean by "hiding"? There are types that use different internal representation (for c# - decimal) that do not loose precision. Probably, there is similar type in Java (BigDecimal is suitable i think) . But I'm not sure is precision issue can be hidden. You can check this article: http://discuss.joelonsoftware.com/default.asp?design.4.346343.29 it is explained about Java's decimal and I think is still an issue.
anthares
+1  A: 

Not all decimal numbers can be exactly represented using the double floating point format.

In your example the constant 0.1 is the root of the problem. Even if you have written 0.1 in your source-code the next best representation in double-format is 0.1000000000000000056.

Therefore the comparison will never compare to true.

Also note that not only constants have their problems. All arithmetic (addition in your case) have limited precision issues as well.

Nils Pipenbrinck
+1  A: 

Read this (Wikipedia). Print it out and sleep with it under your pillow for a couple of months.

Tim Schaeffer
+1  A: 

For the detailed view: What Every Computer Scientist Should Know About Floating Point

Steve Fallows