Floating-Point arithmetic in dlang - Difference to other languages
H. S. Teoh
hsteoh at quickfur.ath.cx
Tue Dec 3 18:45:42 UTC 2019
On Tue, Dec 03, 2019 at 09:22:49AM +0000, Jan Hönig via Digitalmars-d-learn wrote:
> Today i have stumbled on Hacker News into: https://0.30000000000000004.com/
> I am learning D, that's why i have to ask.
> Why does
> writefln("%.17f", .1+.2);
> not evaluate into: 0.30000000000000004, like C++
> but rather to: 0.29999999999999999
> Many other languages evaluate to 0.30000000000000004 as well.
In short, because they use 64-bit floats for intermediate values
(`double`), whereas D defaults to 80-bit intermediates (`real`).
The use of a more precise intermediate value is also indicated by the
fact that 0.29999999999999999 is closer to the real answer (error of
1e-17) than 0.30000000000000004 (error of 4e-17).
If you explicitly specify to use `double`, then you should get the same
answer as C++.
double a=.1, b=.2;
MSDOS = MicroSoft's Denial Of Service
More information about the Digitalmars-d-learn