Skip to content Skip to sidebar Skip to footer

Doing Accurate Floating Point Division In Python 3

Is there a way to do accurate floating point division in Python? Let's say I try to do the following mathematical operations. 0.6 / 0.3 returns 2.0 which is correct. Cool, it look

Solution 1:

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.

fromdecimal 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.

Post a Comment for "Doing Accurate Floating Point Division In Python 3"