双重计算问题 [英] double calculation issue
本文介绍了双重计算问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,在我的C ++代码中,我有2个双变量,其值分别为.4和.1
当我从.4中减去.1时,我得到的值是.30000000004.请问为什么编译器给出了这样的值以及如何解决这个问题.
例如代码
double d = .4; double dec = .1 double result = d- dec;
因此,当我从.1中减去.1时,我得到的是.00000000027而不是zeo.它们存储在二进制文件中.这意味着以10为底的精确数字在以2为底的数字中不是那么精确:
在此处 [
如果计算精度很重要,建议您编写或找到一个使用整数分子和分母处理有理数的类.这样,您就可以消除舍入误差,或者至少推迟舍入误差直到出现.
对
float
或double
的100%精度计算是不可能的,而且永远不可能.你必须忍受那个.
阅读该书以了解浮点运算的工作原理:
http://en.wikipedia.org/wiki/Floating_point [ 解决方案
It happens because numbers aren''t stored in base ten - they are stored in binary. This means that what is a precise number is base 10 is not so precise in base 2:
There is a guide to the details here[^] which explains it better than I could: see about half way down under "Converting Decimal Fractions to Binary Reals"
If calculation accuracy is important, I suggest you write or find a class that handles rational numbers, using an integer numerator and denominator. That way you can rid yourself of, or a least postpone, the rounding error until presentation.
100% precision computation onfloat
ordouble
are not possible and will never be. You have to live with that.
Read that to understand how floating point operations work:
http://en.wikipedia.org/wiki/Floating_point[^]
If you don''t want any rounding errors, then I suggest you to work withint
,long
, orint64
types.
这篇关于双重计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文