小编mag*_*852的帖子

如何在Python中获得更精确的十进制值

from math import sqrt


a=1e-8
b=10
c=1e-8

x1 = ((-b)-sqrt((b**2)-(4*a*c)))/(2*a)
x2 = ((-b)+sqrt((b**2)-(4*a*c)))/(2*a)

print 'x1 = {}'.format(x1)
print 'x2 = {}'.format(x2)

print (4*a*c)
print (sqrt(b**2-4*a*c))
print b**2
print 2*a
Run Code Online (Sandbox Code Playgroud)

当我运行该程序时,它返回:

x1 = -1e+09
x2 = 0.0

4e-16
10.0
100.0
2e-08
Run Code Online (Sandbox Code Playgroud)

我需要的是x2等于-1e-9.

问题似乎与

sqrt((b**2)-(4*a*c))
Run Code Online (Sandbox Code Playgroud)

因为它给出10作为结果,显然因为4*(10 ^ -8)*(10 ^ -8)几乎等于0,并且被python认为是0.

这导致:

sqrt((b**2)-(4*a*c)) = sqrt(b**2) = sqrt(10**2) = 10
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

python math calculus

3
推荐指数
2
解决办法
571
查看次数

标签 统计

calculus ×1

math ×1

python ×1