繁体   English   中英

Python中的二次方程

[英]Second degree equation in 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计算错误。 如何解决此舍入错误?

您的问题是由于浮点精度问题引起的。 您可以在这里阅读更多内容-https: //docs.python.org/2/tutorial/floatingpoint.html

您可以通过四舍五入来克服这一点-

>>> round(numerator2, 3)
-0.0

我相信您可能会在这篇文章中找到一些答案: 带浮点数的Python舍入错误

此外,您应注意:

>>> print square 10

>>> square 9.999999999999801

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM