How to square or raise to a power (elementwise) a 2D numpy array?

前端 未结 2 1238
遥遥无期
遥遥无期 2021-02-02 06:42

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         


        
2条回答
  •  旧时难觅i
    2021-02-02 07:15

    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() 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.

    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
    

提交回复
热议问题