快速检查
从签名中,我们可以看出它们是不同的:
pow(x, y[, z])
数学.pow(x, y)
此外,在 shell 中尝试它会给你一个快速的想法:
>>> pow is math.pow
False
测试差异
了解这两个函数之间行为差异的另一种方法是测试它们:
import math
import traceback
import sys
inf = float("inf")
NaN = float("nan")
vals = [inf, NaN, 0.0, 1.0, 2.2, -1.0, -0.0, -2.2, -inf, 1, 0, 2]
tests = set([])
for vala in vals:
for valb in vals:
tests.add( (vala, valb) )
tests.add( (valb, vala) )
for a,b in tests:
print("math.pow(%f,%f)"%(a,b) )
try:
print(" %f "%math.pow(a,b))
except:
traceback.print_exc()
print("__builtins__.pow(%f,%f)"%(a,b) )
try:
print(" %f "%__builtins__.pow(a,b))
except:
traceback.print_exc()
然后我们可以注意到一些细微的差异。例如:
math.pow(0.000000,-2.200000)
ValueError: math domain error
__builtins__.pow(0.000000,-2.200000)
ZeroDivisionError: 0.0 cannot be raised to a negative power
还有其他区别,上面的测试列表并不完整(没有长数字,没有复杂等等),但这会给我们一个实用的列表,说明这两个函数的行为方式有何不同。我还建议扩展上述测试以检查每个函数返回的类型。您可能会编写类似的东西来创建两个函数之间差异的报告。
math.pow()
math.pow()
处理它的参数与内置的**
或pow()
. 这是以灵活性为代价的。查看源代码,我们可以看到 to 的参数math.pow()
直接转换为双精度:
static PyObject *
math_pow(PyObject *self, PyObject *args)
{
PyObject *ox, *oy;
double r, x, y;
int odd_y;
if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
return NULL;
x = PyFloat_AsDouble(ox);
y = PyFloat_AsDouble(oy);
/*...*/
然后对双精度进行有效性检查,然后将结果传递给底层的 C 数学库。
内置pow()
另一方面,内置pow()
(与运算符相同)的行为非常不同,它实际上使用对象自己的运算符实现,如果需要,最终用户可以通过替换数字的或方法来覆盖它。**
**
__pow__()
__rpow__()
__ipow__()
对于内置类型,研究为两种数字类型(例如floats、long和complex )实现的幂函数之间的区别是有益的。
覆盖默认行为
此处描述了模拟数字类型。本质上,如果您要为不确定的数字创建新类型,您需要做的是为您的类型提供__pow__()
,__rpow__()
和可能__ipow__()
的方法。这将允许您的号码与运营商一起使用:
class Uncertain:
def __init__(self, x, delta=0):
self.delta = delta
self.x = x
def __pow__(self, other):
return Uncertain(
self.x**other.x,
Uncertain._propagate_power(self, other)
)
@staticmethod
def _propagate_power(A, B):
return math.sqrt(
((B.x*(A.x**(B.x-1)))**2)*A.delta*A.delta +
(((A.x**B.x)*math.log(B.x))**2)*B.delta*B.delta
)
为了覆盖math.pow()
,您必须对其进行修补以支持您的新类型:
def new_pow(a,b):
_a = Uncertain(a)
_b = Uncertain(b)
return _a ** _b
math.pow = new_pow
请注意,要使其正常工作,您必须与Uncertain
类争吵以处理Uncertain
实例作为输入__init__()