如何在Python中获得更精确的十进制值
发布时间:2020-12-20 12:09:05 所属栏目:Python 来源:网络整理
导读:from math import sqrta=1e-8b=10c=1e-8x1 = ((-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**2print 2*a 当我运行该程序时,
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |