tags:

views:

66

answers:

6

i have read that some machine can't express exaclty floating point number for example 1.1 let's take code

float x=0.1;
do{

x+=0.1;
printf("%f\n",x);
} while(x!=1.1); 

this code never finished how can i make that code finish? maybe convert it to double or?

+2  A: 

For example, compare within an acceptable margin. I.e.

while (abs(x-1.1)>0.001);

Doubles will have the same issue, just with more precision. Some languages also offer you rational types, where you can specify a number as the fraction 1/10, or fixed point data types.

relet
A: 

In this case, checking "<" will do the trick:

float x=0.1;
do{

x+=0.1;
printf("%f\n",x);
} while(x<1.05); 

In general, you should test against an "epsilon". Look here for further information.

Doc Brown
A: 

Read this: http://docs.python.org/tutorial/floatingpoint.html (Never mind that it's in the Python site.)

lhf
A: 

If you want to do code precisely like you are saying then you want to use a type like decimal (where available) which is a base 10 floating point implementation rather than a base 2.

Further reading: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems and http://en.wikipedia.org/wiki/Decimal_floating_point

Chris
A: 

Work in fixed point, for that kind of task.

The decimal type for example might help. It's not the solution for all problems though.

Mau
+3  A: 

For numerical problems, it is common to specify an epsilon of accuracy:

bool within_epsilon(float x, float y, float e) {
    if (abs(x - y) > e) {
        return false
    } else {
        return true
    }
}

The epsilon you choose will change your accuracy, and the epsilon you can choose is dependent on your floating point implementation: Machine epsilon.

tkerwin
+1 for referring to epsilon, since this will enable people to google for this information in an easier way
davbryn