如何为方形或提高到一个电源(按元素)一个二维数组numpy的? [英] How to square or raise to a power (elementwise) a 2D numpy array?
问题描述
我需要一个方形二维numpy的阵列(按元素),我曾尝试以下code:
I need to square a 2D numpy array (elementwise) and I have tried the following code:
import numpy as np
a = np.arange(4).reshape(2, 2)
print a^2, '\n'
print a*a
这收益率:
[[2 3]
[0 1]]
[[0 1]
[4 9]]
显然,符号 A * A
给我我想要,结果不是 A ^ 2
。
Clearly, the notation a*a
gives me the result I want and not a^2
.
我想知道,如果另一个符号的存在是为了筹集numpy的阵列的2或N的力量?取而代之的 A * A * A *。* A
。
I would like to know if another notation exists to raise a numpy array to the power of 2 or N? Instead of a*a*a*..*a
.
推荐答案
最快的方法是做 A * A
或 A ** 2
或 np.square(一)
,而 np.power(一,二)
显示是相当慢。
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
允许您使用不同的指数为每一个元素,如果不是 2
您通过另一阵指数的。从@GarethRees的意见,我刚刚得知这个功能会给你比 A ** 2
或 A * A $ C $不同的结果C>,这成为在您有公差小的情况下非常重要的。
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
我使用numpy的1.9.0 MKL 64位定时一些例子中,其结果如下所示:
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
这篇关于如何为方形或提高到一个电源(按元素)一个二维数组numpy的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!