float precision loss problem to solve, with decimal.Decimal

First look at a floating-point operations: The following, when the two type float, calculates, accuracy can not be guaranteed

a = 0.1
b = 0.3
print(a)
print(b)
print(b-a)

 

So, how to make the above subtraction value, we want to give it 0.2? Importing decimal module, if either lose precision Decimal class must be received it is str type, or if the incoming float type, then the accuracy will still lose

 

import decimal
a = 0.1
b = 0.3
print(decimal.Decimal(str(b)) - decimal.Decimal(str(a)))
print(decimal.Decimal(b) - decimal.Decimal(a))

Guess you like

Origin www.cnblogs.com/xiaofeng91/p/12051898.html