1

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:

11.999999998
  • You can't. `float` is inherently imprecise (and where it's precise, it's *binary* precise, not *decimal* precise). Try the `decimal` module (which will still be imprecise but with greater, and configurable, precision, with the imprecision occurring in more predictable ways) or the `fractions` module (which is 100% precise, but can rapidly consume a *lot* of memory and computational time if you perform many computations). – ShadowRanger Dec 13 '21 at 01:09
  • Take a look at https://stackoverflow.com/questions/11522933/is-floating-point-arbitrary-precision-available – Chris Dec 13 '21 at 01:10

1 Answers1

0

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

kosciej16
  • 6,294
  • 1
  • 18
  • 29
  • `12 == x / y` evaluates to `True` in your code as written; if it didn't, `Decimal` would have lost precision (which can happen for infinitely repeating decimals or decimals that are longer than the configured precision, but won't happen here). – ShadowRanger Jan 13 '22 at 20:34