Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

store, compute and display the result of Floating Point Arithmetic issues for Python

I’ve understood there’re several questions/answers available with similar headlines for C++, JS, and Java in SO but I’d like to know the right Pythonic way to address the aspect of storing variables, recomputing with another float var, and presenting them. I list the examples below. if there’s a duplicate for Python, please let me know too and I’ll close this. Thank you.

1. First Example

Expecting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In[1]: a = 0.35 + 0.1
In[2]: print(a)
0.45

Actual:

In[1]: a = 0.35 + 0.1
In[2]: print(a)
0.44999999999999996

My take to present:

format(a, '.2f')
'0.45'

I thought Decimal could help but it looks like the same

In[1]:import decimal
      from decimal import Decimal

In[2]:Decimal(0.35) + Decimal(0.1)
Decimal('0.4499999999999999833466546306')

2. Second Example

Expecting:

In[1]:b = 0.35
In[2]:b.as_integer_ratio()
(7, 20)

Actual:

In[1]:b = 0.35
In[2]:b.as_integer_ratio()
(3152519739159347, 9007199254740992)

>Solution :

You are starting with imprecise floats. Start with exact decimals, from string representation:

Decimal("0.35") + Decimal("0.1")
# => Decimal('0.45')

Decimal("0.35").as_integer_ratio()
# => (9, 20)

Or start with exact numbers (e.g. integers):

Decimal(35) / Decimal(100)
# => Decimal('0.35')

from fractions import Fraction
Fraction(35, 100)
# => Fraction(7, 20)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading