Python numpy.square vs **
Question:
Is there a difference between numpy.square
and using the **
operator on a Numpy array?
From what I can see it yields the same result.
Any differences in efficiency of execution?
An example for clarification:
In [1]: import numpy as np
In [2]: A = np.array([[2, 2],[2, 2]])
In [3]: np.square(A)
Out[3]:
array([[4, 4],
[4, 4]])
In [4]: A ** 2
Out[4]:
array([[4, 4],
[4, 4]])
Answers:
For most appliances, both will give you the same results.
Generally the standard pythonic a*a
or a**2
is faster than the numpy.square()
or numpy.pow()
, but the numpy
functions are often more flexible and precise.
If you do calculations that need to be very accurate, stick to numpy
and probably even use other datatypes float96
.
For normal usage a**2
will do a good job and way faster job than numpy
.
The guys in this thread gave some good examples to a similar questions.
You can check the execution time to get clear picture of it
In [2]: import numpy as np
In [3]: A = np.array([[2, 2],[2, 2]])
In [7]: %timeit np.square(A)
1000000 loops, best of 3: 923 ns per loop
In [8]: %timeit A ** 2
1000000 loops, best of 3: 668 ns per loop
@saimadhu.polamuri and @foehnx/@Lumos
On my machine, currently, NumPy performs faster than **.
In [1]: import numpy as np
In [2]: A = np.array([[1,2],[3,4]])
In [3]: %timeit A ** 2
256 ns ± 0.922 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit np.square(A)
240 ns ± 0.759 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Is there a difference between numpy.square
and using the **
operator on a Numpy array?
From what I can see it yields the same result.
Any differences in efficiency of execution?
An example for clarification:
In [1]: import numpy as np
In [2]: A = np.array([[2, 2],[2, 2]])
In [3]: np.square(A)
Out[3]:
array([[4, 4],
[4, 4]])
In [4]: A ** 2
Out[4]:
array([[4, 4],
[4, 4]])
For most appliances, both will give you the same results.
Generally the standard pythonic a*a
or a**2
is faster than the numpy.square()
or numpy.pow()
, but the numpy
functions are often more flexible and precise.
If you do calculations that need to be very accurate, stick to numpy
and probably even use other datatypes float96
.
For normal usage a**2
will do a good job and way faster job than numpy
.
The guys in this thread gave some good examples to a similar questions.
You can check the execution time to get clear picture of it
In [2]: import numpy as np
In [3]: A = np.array([[2, 2],[2, 2]])
In [7]: %timeit np.square(A)
1000000 loops, best of 3: 923 ns per loop
In [8]: %timeit A ** 2
1000000 loops, best of 3: 668 ns per loop
@saimadhu.polamuri and @foehnx/@Lumos
On my machine, currently, NumPy performs faster than **.
In [1]: import numpy as np
In [2]: A = np.array([[1,2],[3,4]])
In [3]: %timeit A ** 2
256 ns ± 0.922 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit np.square(A)
240 ns ± 0.759 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)