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?

  • You are not supposed to use equality comparisons on floating point numbers. – phkahler Jul 30 '10 at 14:06
  • This is my favorite explanation of why floating point numbers, of any precision or type, cannot exactly represent all real numbers: http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary/1089026#1089026 – mtrw Jul 30 '10 at 16:55

5 Answers5

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.

tkerwin
  • 9,559
  • 1
  • 31
  • 47
  • +1 for referring to epsilon, since this will enable people to google for this information in an easier way – davbryn Jul 30 '10 at 13:30
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.

relet
  • 6,819
  • 2
  • 33
  • 41
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.

Doc Brown
  • 19,739
  • 7
  • 52
  • 88
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.

Mau
  • 14,234
  • 2
  • 31
  • 52
-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

Chris
  • 27,210
  • 6
  • 71
  • 92