本文介绍了在python中,标量的math.acos()比numpy.arccos()快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用大量几何计算在Python中进行一些科学计算,并且遇到了使用numpy与标准math库之间的显着差异.

I'm doing some scientific computing in Python with a lot of geometric calculations, and I ran across a significant difference between using numpy versus the standard math library.

>>> x = timeit.Timer('v = np.arccos(a)', 'import numpy as np; a = 0.6')
>>> x.timeit(100000)
0.15387153439223766
>>> y = timeit.Timer('v = math.acos(a)', 'import math; a = 0.6')
>>> y.timeit(100000)
0.012333301827311516

那是10倍以上的加速速度!我对几乎所有标准数学函数都使用了numpy,我只是假设它已经过优化并且至少与math一样快.对于足够长的向量,numpy.arccos()最终会胜过使用math.acos()进行循环,但是由于我仅使用标量大小写,因此使用math.acos(),math.asin()会有任何不利之处,全面的math.atan()而不是numpy版本?

That's more than a 10x speedup! I'm using numpy for almost all standard math functions, and I just assumed it was optimized and at least as fast as math. For long enough vectors, numpy.arccos() will eventually win vs. looping with math.acos(), but since I only use the scalar case, is there any downside to using math.acos(), math.asin(), math.atan() across the board, instead of the numpy versions?

推荐答案

math模块中的函数用于标量是完全可以的. numpy.arccos 函数可能由于

Using the functions from the math module for scalars is perfectly fine. The numpy.arccos function is likely to be slower due to

  • conversion to an array (and a C data type)
  • C function call overhead
  • conversion of the result back to a python type

如果这种性能差异对您的问题很重要,则应检查是否真的不能使用数组操作.正如 user2357112 在注释,数组是numpy真正擅长的地方.

If this difference in performance is important for your problem, you should check if you really can't use array operations. As user2357112 said in the comments, arrays are what numpy really is great at.

这篇关于在python中,标量的math.acos()比numpy.arccos()快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:33