在Python中,浮点数运算可能存在精度问题,可以采取以下方法解决:
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浮点数运算精度问题。