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

How can I consistently get correct float division in python3?

I am trying to divide floats by each other but am having a hard time getting accurate results. I understand that computers store floats in a way where the value stored is not exact to the given number. I am simply looking for a way where I can get specific results when working with floats.

input:

x = 2.4
y = 0.2
print(x/y)

Output:

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

11.999999998

>Solution :

I highly recommend to use decimals

Example

from decimal import Decimal

x = Decimal("2.4")
y = Decimal("0.2")
print(x / y) # 12

Notice we passing number as string, as passing float numbers would have the same problem you pointed out.
But care with comparison, as 12 == x / y evaluates to False

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