Tuesday 23 July 2019

floating point - Make Python aritmetic operations

This is a result of the fact that many decimals cannot be exactly represented in binary.


For example, 0.25 can: it's 0.01 (0*1, 0*1/2, 1*1/4). 0.1 can't (0.0001100110011...), just like you can't write 1/3 as a complete decimal (0.3333333333...).


If you do


print(12.45-12)

you get


0.45

because print only displays the first significant digits.


See the Python docs for an excellent summary.


If you do care about decimal values being exact (for example to avoid a Superman III scenario in a financial institution), look at the Decimal module.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...