assert(0.1 + 0.2 != 0.3); // shall be true
is my favorite check that a language uses native floating point arithmetic.
#include <cstdio>
int main()
{
printf("%d\n", (0.1 + 0.2 != 0.3));
return 0;
}
Output:
1
print(0.1 + 0.2 != 0.3)
Output:
True
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.
import std.stdio;
void main()
{
writeln(0.1 + 0.2 != 0.3);
}
Output:
false
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.