Python中的二次方程
我想在Python中计算这个二次方程:
10^-6x^2 + 10x + 10^-6 = 0
用已知的公式在Python中写出来大概是这样的:
#This is just a small part of the program#
a = 10.**-6
b = 10.
c = 10.**-6
square = sqrt((b**2) - (4.*a*c))
numerator1 = -b - square
numerator2 = -b + square
denominator = 2.*a
print square
print numerator1
print numerator2
现在我有个问题:因为四舍五入的误差,我的
square = 10.0
numerator1 = -20
numerator2 = -1.98951966013e-13
为什么我的第二个分子差得这么远?-b在两种情况下都是一样的……这会导致我的x2计算错误。我该如何修复这个四舍五入的误差呢?
2 个回答
0
你的问题是因为浮点数精度的问题。你可以在这里了解更多相关内容 - https://docs.python.org/2/tutorial/floatingpoint.html
你可以通过四舍五入来稍微解决这个问题 -
>>> round(numerator2, 3)
-0.0
0