I tried :
x = 3.4
print(x - math.floor(x))
In both in console and Jupyter Notebook, the result shows 0.3999999999999999
but why not just 0.4
as the result.
Thanks.
I tried :
x = 3.4
print(x - math.floor(x))
In both in console and Jupyter Notebook, the result shows 0.3999999999999999
but why not just 0.4
as the result.
Thanks.
It is actually not due to python but is inherent to how floats are implemented and would also happen in javascript for instance.
This explanation should answer your question: https://floating-point-gui.de/basic/
If you need to handle it as a decimal, as pointed out you should check the decimal
module, or you could round the final result before rendering.
To get 0.4
you can use the decimal
module:
>>> import decimal
>>> x = decimal.Decimal('3.4')
>>> print(x - math.floor(x))
Decimal('0.4')