Python numpy.square vs **

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29361856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:28:50  来源:igfitidea点击:

Python numpy.square vs **

pythonnumpy

提问by Skeppet

Is there a difference between numpy.squareand using the **operator on a Numpy array?

在 Numpy 数组上numpy.square使用**运算符和使用运算符有区别吗?

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]])

采纳答案by saimadhu.polamuri

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

回答by foehnx

For most appliances, both will give you the same results. Generally the standard pythonic a*aor a**2is faster than the numpy.square()or numpy.pow(), but the numpyfunctions are often more flexible and precise. If you do calculations that need to be very accurate, stick to numpyand probably even use other datatypes float96.

对于大多数电器,两者都会给您相同的结果。通常的标准Python化a*aa**2比快numpy.square()numpy.pow(),但numpy功能往往更灵活和精确的。如果您进行需要非常准确的计算,请坚持numpy甚至可能使用其他数据类型float96

For normal usage a**2will do a good job and way faster job than numpy. The guys in this threadgave some good examples to a similar questions.

对于正常使用,a**2会比numpy. 在这些家伙的主题提出了一些很好的例子,一个类似的问题。