the start (of some activity)
A common problem with floating point numbers is that they cannot represent decimal numbers exactly.
>>> a = 4.2 >>> b = 2.1 >>> a + b 6.300000000000001 >>> (a + b) == 6.3 False >>>
This is due to the fact that the underlying CPU andIEEE 754 The standard is characterized by performing arithmetic in its own floating-point units. A seemingly infinite number of decimals is infinite in the computer's binary representation.
Normally, this little bit of small error is allowed to exist. If this kind of error cannot be tolerated (e.g. in finance), then it is time to consider some ways to solve this problem.
Decimal
There are no small errors with this module.
>>> from decimal import Decimal >>> a = Decimal('4.2') >>> b = Decimal('2.1') >>> a + b Decimal('6.3') >>> print(a + b) 6.3 >>> (a + b) == Decimal('6.3') True
Although the code looks strange, using strings to represent numbers, theDecimal
All common math operations are supported.decimal
module allows you to control every aspect of the calculation, including number digits and rounding. Before doing so, you need to create a temporary contextual environment to change this setting:
>>> from decimal import Decimal, localcontext >>> a = Decimal('1.3') >>> b = Decimal('1.7') >>> print(a / b) 0.7647058823529411764705882353 >>> with localcontext() as ctx: ... = 3 ... print(a / b) ... 0.765 >>> with localcontext() as ctx: ... = 50 ... print(a / b) ... 0.76470588235294117647058823529411764705882352941176 >>>
due toDecimal
of high-precision numbers naturally use strings for presentation and transit as well.
summarize
Overall, when it comes to the financial sector, even a small margin of error is not allowed in the calculation process. Thereforedecimal
The module provides a way to address such issues.
Above is the exact floating point arithmetic example in python in detail, more information about python floating point arithmetic please pay attention to my other related articles!