奇怪的 python 电源模块结果

Weird python power module result

根据 these 的回答,pow(a,b)a**b 之间没有区别。但是,math.pow(a,b) returns 是一个浮点值。现在,当 运行 下面的 python 代码发生了一些奇怪的事情:

>>>import math
>>>math.pow(19,13)%2537
2296.0
>>>pow(19,13)%2537
2299

这些语句应该给出相同的值,但事实并非如此。关于为什么会发生这种情况的任何线索?

如您所说,math.pow returns 是浮点值,而 pow 不是。在浮点数上调用模运算符会将其舍入为整数。将浮点数舍入为整数会导致精度损失。

>>> int(math.pow(19,13))
42052983462257056
>>> pow(19,13)
42052983462257059

math.pow() 将其参数转换为 float:

>>> import math
>>> import fractions
>>> math.pow(fractions.Fraction(3, 2), 2)
2.25

但内置 pow 不会:

>>> pow(fractions.Fraction(3, 2), 2)
Fraction(9, 4)

同时检查:Difference between the built-in pow() and math.pow() for floats, in Python?

float 类型失去精度。它们由最接近的二进制分数和文档 Floating Point Arithmetic: Issues and Limitations

表示

Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction.

您可以通过 math.pow(19,13) 的结果清楚地看到问题,其中多个整数映射到同一个浮点数。

>>> f = math.pow(19,13)
>>> float(int(f)) == float(int(f) - 1)
True
>>> float(int(f)) == float(int(f) - 2)
True
>>> float(int(f)) == float(int(f) - 3)
True
>>> float(int(f)) == float(int(f) - 4)
True
>>> float(int(f)) == float(int(f) - 5)
False

由于python可以处理非常大的整数,所以尽量远离浮点数!​​