如何在Python中获得更精确的十进制值 [英] How can I get more exact decimal values in Python
本文介绍了如何在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
当我运行程序时,将返回:
When I run the program, this returns:
x1 = -1e+09
x2 = 0.0
4e-16
10.0
100.0
2e-08
我需要的是x2等于-1e-9.
What I need is for x2 to be equal to -1e-9.
问题似乎出在
sqrt((b**2)-(4*a*c))
结果是10,显然是因为4 *(10 ^ -8)*(10 ^ -8)几乎等于0,并且被python认为是0.
as it gives 10 as a result, obviously because 4*(10^-8)*(10^-8) is almost equal to 0, and is considered 0 by python.
结果是:
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中获得更精确的十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文