Python math.pow() 失去计算精度

Python math.pow() losing calculation percision

我的代码:

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.

这是比较它们的更好方法

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

看过很多关于Python 3自动将int转bignum的东西,但是bignum好像不够用。我也试过 19 ** 19。它计算出相同的错误数字。

有人可以帮助我吗?

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

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