1

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
  • You are not supposed to use equality comparisons on floating point numbers. Commented Jul 30, 2010 at 14:06
  • This is my favorite explanation of why floating point numbers, of any precision or type, cannot exactly represent all real numbers: stackoverflow.com/questions/1089018/… Commented Jul 30, 2010 at 16:55

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

0

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.

Comments

0

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.

Comments

-1

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

Comments