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
Decimal('0.6') / Decimal('0.3')
returnsDecimal('2')
which is correct.Decimal('0.6') / Decimal('0.2')
returnsDecimal('3')
which is correct.Decimal('0.6') / Decimal('0.1')
returnsDecimal('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"