如何在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
当我运行该程序时,它返回:
x1 = -1e+09
x2 = 0.0
4e-16
10.0
100.0
2e-08
我需要的是x2等于-1e-9.
问题似乎与
sqrt((b**2)-(4*a*c))
因为它给出10作为结果,显然因为4 *(10 ^ -8)*(10 ^ -8)几乎等于0,并且被python认为是0.
这导致:
sqrt((b**2)-(4*a*c)) = sqrt(b**2) = sqrt(10**2) = 10
任何帮助将不胜感激
解决方法:
使用十进制模块:
from decimal import Decimal
a = Decimal('1E-8')
b = 10
c = Decimal('1E-8')
x1 = ((-b)-((b**2)-(4*a*c)).sqrt())/(2*a)
x2 = ((-b)+((b**2)-(4*a*c)).sqrt())/(2*a)
print 'x1 = {}'.format(x1)
print 'x2 = {}'.format(x2)
结果是
x1 = -999999999.999999999000000000
x2 = -1.0000000000E-9
标签:python,math,calculus 来源: https://codeday.me/bug/20190716/1475930.html