D为什么0.1 + 0.2 == 0.3? [英] Why 0.1 + 0.2 == 0.3 in D?
本文介绍了D为什么0.1 + 0.2 == 0.3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
assert(0.1 + 0.2!= 0.3); //应该是真的
是我最喜欢的一个语言使用本地浮点算法的检查。 >
C ++
#include< cstdio>
int main()
{
printf(%d \ n,(0.1 + 0.2!= 0.3));
返回0;
$ b $ p $输出:
1
$ b Python
print(0.1 + 0.2!= 0.3)
输出:
True
其他示例
D为什么不是这样?理解D使用本地浮点数。这是一个错误?他们是否使用一些具体的数字表示?别的东西?
D
import std.stdio;
void main()
{
writeln(0.1 + 0.2!= 0.3);
$ b $ p $输出:
false
UPDATE
感谢 LukeH 。这是浮点常量折叠的效果,描述如下 。
代码:
import std.stdio;
void main()
{
writeln(0.1 + 0.2!= 0.3); //常量折叠是以真实精度完成
auto a = 0.1;
auto b = 0.2;
writeln(a + b!= 0.3); //以双精度计算的标准计算
code $
$ p $输出:
false
true
assert(0.1 + 0.2 != 0.3); // shall be true
is my favorite check that a language uses native floating point arithmetic.
C++
#include <cstdio>
int main()
{
printf("%d\n", (0.1 + 0.2 != 0.3));
return 0;
}
Output:
1
Python
print(0.1 + 0.2 != 0.3)
Output:
True
Other examples
Why is this not true for D? As understand D uses native floating point numbers. Is this a bug? Do they use some specific number representation? Something else? Pretty confusing.
D
import std.stdio;
void main()
{
writeln(0.1 + 0.2 != 0.3);
}
Output:
false
UPDATE
Thanks to LukeH. This is an effect of Floating Point Constant Folding described there.
Code:
import std.stdio;
void main()
{
writeln(0.1 + 0.2 != 0.3); // constant folding is done in real precision
auto a = 0.1;
auto b = 0.2;
writeln(a + b != 0.3); // standard calculation in double precision
}
Output:
false
true
解决方案 It's probably being optimized to (0.3 != 0.3). Which is obviously false. Check optimization settings, make sure they're switched off, and try again.
这篇关于D为什么0.1 + 0.2 == 0.3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文