数组的三个参数 pow

no *_*nek 6 python math numpy pow modular-arithmetic

pow接受模数的第三个参数,pow(x, y, z)该参数比 更有效的计算x ** y % z。你怎么能用数组做到这一点?我试过的:

>>> import numpy as np
>>> A = np.array(range(10))
>>> pow(A, 23, 13)
TypeError: unsupported operand type(s) for pow(): 'numpy.ndarray', 'int', 'int'
Run Code Online (Sandbox Code Playgroud)

虽然 ndarray 实现了__pow__,直接调用不会做任何事情:

>>> A.__pow__(23, 13)
NotImplemented
Run Code Online (Sandbox Code Playgroud)

在两步中使用求幂和取模会产生不正确的结果(猜测它正在溢出 dtype)

>>> print(*(A ** 23 % 13))  # wrong result!
0 1 7 9 10 8 11 12 0 6
>>> print(*[pow(int(a), 23, 13) for a in A])  # correct result
0 1 7 9 10 8 11 2 5 3
Run Code Online (Sandbox Code Playgroud)

实际数组很大,所以我不能使用 dtype“object”,也不能直接在 Python 中循环。

如何计算 numpy 数组的 3-arg pow?

myz*_*540 -1

您可以使用map()lambda 来完成此操作。然后您可以一次使用一个结果。尝试:

result_iter = map(lambda x: pow(int(x), 23, 13), A))

results = list(result_iter)
print(results)
Run Code Online (Sandbox Code Playgroud)

输出:

[0, 1, 7, 9, 10, 8, 11, 2, 5, 3]
Run Code Online (Sandbox Code Playgroud)

  • 这是可行的,但相对于 numpy 中的矢量化解决方案来说,它会慢得多。 (3认同)