C / C ++浮点问题 [英] C/C++ floating point issue
问题描述
我一个基本的浮点precision问题挣扎。这里的问题是:
I am struggling with a basic floating-point precision issue. Here is the problem:
double d = 0.1;
d += 0.1;
d += 0.1;
d == 0.3 ? std::cout << "yes" : std::cout << "no";
运行code,你会得到没有
Run the code and you get "no"
据我了解,在二进制和二进制存储C / C ++存储值不能准确存储每个值。我也明白,这些小错误化合物你他们做各种数学运算(即D + = 0.1;)
I understand that C/C++ store values in binary and that binary storage can not exactly store every value. I also understand that these small errors compound as you do various math operations on them (i.e. d += 0.1;).
我的问题是,如果我需要测试当d = = 0.3(一个合理的precision ..因为是code的明确意图以上)......我该怎么办呢?我希望答案是不是:
My questions is if I do need to test if d == 0.3 (to a reasonable precision.. as is the clear intent of code above)... how do I do that? I hope the answer is not:
if (d > 0.2999 && d < 0.3001) ...
还..这个作品
float f = 0.1;
f += 0.1;
f += 0.1;
f == 0.3f ? std::cout << "yes" : std::cout << "no";
但我能找到的语言中没有对等0.3D。
but I can find no equivalent "0.3d" in the language.
感谢
推荐答案
测试平等一定的耐受度的一种常用方法是使用的 晶圆厂
:
One common way of testing equality to a certain "tolerance level" is using fabs
:
if (fabs(d - 0.3) < 1E-8) {
...
}
这篇关于C / C ++浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!