Python math.pow()失去计算percision

时间:2016-08-09 21:10:51

标签: python precision

我的代码:

import math

def calculate(operator, firstValue, secondValue):
    if operator == '^':
        toReturn = math.pow(firstValue, secondValue)
    . . .
    return toReturn

. . . 
new = calculate('^', 19, 19)
print('   is ' + str(new))
workingStack.append(int(new))
print('New stack is ' + str(workingStack))

结果

"   is 1.9784196556603136e+24" 
New stack is [16, 14, 1978419655660313627328512]

这对于格式化的字符串很好,但是当我实际使用该变量时,它显示它正在丢失数字的精度,因为你可以看到它将math.pow(19,19)计算为1978419655660313627328512,但它应该是1978419655660313589123979。

这是比较它们的更好方法

  • 1978419655660313627328512< - 计算值
  • 1978419655660313589123979< - 真值

您可以看到错误发生在科学记数法在上面打印结果中失去精确度的地方。我需要能够在其他计算中使用变量的真值。

我已经阅读了许多关于Python 3自动将int转换为bignum的内容,但bignum似乎还不够。我也试过19 ** 19。它以相同的错误数计算。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

math.pow进行有限精度的浮点计算,改为使用幂运算符:

def calculate(operator, firstValue, secondValue):
    if operator == '^':
        toReturn = firstValue ** secondValue
    return toReturn