1

Is there a way to do accurate floating point division in Python?

Let's say I try to do the following mathematical operations.

  1. 0.6 / 0.3 returns 2.0 which is correct. Cool, it looks like math is working!
  2. 0.6 / 0.2 returns 2.9999999999999996 when 3.0 would be the correct result.
  3. 0.6 / 0.1 returns 5.999999999999999 when 6.0 would be the correct result.

I'm wondering if there is a simple solution to this issue that I'm totally missing?

Note: I have seen the answers for Is floating point math broken? and although many of the answers do an outstanding job of explaining floating point operations, it does not appear that any of the responses provide an actual solution on how to accurately do division with floating point values in Python.

Community
  • 1
  • 1
Gunther
  • 2,474
  • 4
  • 31
  • 45
  • 1
    does this help ? http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Whud Nov 25 '16 at 15:50
  • use `round((0.6 / 0.3),4)` this will do the division with 4 digits precisions. – Ja8zyjits Nov 25 '16 at 15:51
  • I'm voting to close this as a duplicate. Note that if you really need arbitrary precision, you can use the module `decimal`. There is no free lunch -- computations are slower if you go that route. – John Coleman Nov 25 '16 at 16:03
  • Hi @JohnColeman, I think the `decimal` module may provide an optimally accurate solution when calculating these results. Thank you for suggesting it as I did not see it mentioned in any of the top answers to the related question. – Gunther Nov 25 '16 at 16:39
  • 3
    The problem is not that the division is not accurately performed but that decimal fractions you type in cannot be exactly represented in a regular float. – smernst Nov 25 '16 at 16:45

1 Answers1

4

Python's decimal library provides functionality to calculate more accurate results when floating point division would otherwise provide less accurate results.

Here is an example that shows the decimal library returning the correct results to a few floating point values being divided.

from decimal import Decimal
  1. Decimal('0.6') / Decimal('0.3') returns Decimal('2') which is correct.
  2. Decimal('0.6') / Decimal('0.2') returns Decimal('3') which is correct.
  3. Decimal('0.6') / Decimal('0.1') returns Decimal('6') which is correct.

As @JohnColeman noted, using the decimal module for these calculations will provide more accureate results, but at the expense of the speed at which the claculations are executed.

Gunther
  • 2,474
  • 4
  • 31
  • 45