by mtreis86 · 5y ago · 0 comments
Powershell says 0.2,
calc.exe app and libreoffice calc agree with 0.2,
BC running in CYGWin also 0.2,
Python 2 and 3 answer 0.19999999999999998,
JS in Vivaldi and firefox also answer 0.19999999999999998,
But Portacle (Common Lisp) returns 0.20000002
- if you get 0.2, the code is using rational numbers or a custom implementation
- 0.199999...8 is the double precision IEEE subtraction.
- 0.200000...2 is the single precision IEEE subtraction.
This looks like a typecasting/coercion issue. You can likely get all of the above in C++ or Java by using different explicit casts.
IIRC, there are languages that use IEEE double precision but the way they handle default display presents this as 0.2 (basically, they use a display algorithm that displays the shortest decimal expression that has the same double precision representation.)
jshell> new BigDecimal("0.3").subtract(new BigDecimal("0.1"))
$8 ==> 0.2 jshell> .3f-.1f
$1 ==> 0.20000002
We got ourselves a hat trick :) In [1]: from decimal import Decimal as D
In [2]: D('0.3') - D('0.2')
Out[2]: Decimal('0.1')[1] https://medium.com/@raiph_mellor/fixed-point-is-still-an-app...
Floating point implementations can vary not only between languages, but also between different CPUs, if the language relies on the hardware implementation (which is the smart thing to do in most cases).
As a side note: Python's implementation of FP isn't standard-compliant. E.g. when you divide by 5.0 by 0.0, the standard says you should get a +inf. In Python you get an exception.