开发者

floating point operations

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);
}开发者_如何学C while(x!=1.1); 

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


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.


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜