在Python中,浮點數(shù)運算可能存在精度問題,可以采取以下方法解決:
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
c = a + b
print(c) # 0.3
a = 0.1
b = 0.2
c = round(a + b, 1)
print(c) # 0.3
from fractions import Fraction
a = Fraction(1, 10)
b = Fraction(2, 10)
c = a + b
print(c) # 3/10
import math
a = 0.1
b = 0.2
c = 0.3
print(math.isclose(a + b, c)) # True
通過以上方法可以解決Python浮點數(shù)運算精度問題。