Floating-Point arithmetic in dlang - Difference to other languages

mipri mipri at minimaltype.com
Tue Dec 3 09:52:18 UTC 2019

On Tuesday, 3 December 2019 at 09:22:49 UTC, Jan Hönig 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.

You can get this result in D as well:

   $ rdmd --eval 'double a = .1, b = .2; writefln("%.17f", a+b)'

https://dlang.org/spec/float.html explains it: real (80bit,
'long double' in C) floats are used in your first calculation,
and doubles are used in my revised example.

Most other languages give you the double result for very
reasonable historical reasons, described here:

D's behavior is a minor 'miss': https://nwcpp.org/Oct-2019.html

... I wanted to include a C example that gives the D result,
but it seems to be trickier to force 80 bit intermediates.

More information about the Digitalmars-d-learn mailing list