用Python计算数组的余弦值

2024-06-14 17:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这个数组名为a,共1242个数字。我需要得到Python中所有数字的余弦值。

当我使用:cos_ra = math.cos(a)时,我得到一个错误,说明:

TypeError: only length-1 arrays can be converted to Python scalars

我怎样才能解决这个问题??

提前谢谢


Tags: toonly错误数字mathbecoscan
3条回答

问题是您在这里使用的是numpy.math.cos,它希望您传递一个标量。如果要对iterable应用cos,请使用numpy.cos

In [30]: import numpy as np

In [31]: np.cos(np.array([1, 2, 3]))                                                             
Out[31]: array([ 0.54030231, -0.41614684, -0.9899925 ])

错误:

In [32]: np.math.cos(np.array([1, 2, 3]))                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-8ce0f3c0df04> in <module>()
----> 1 np.math.cos(np.array([1, 2, 3]))

TypeError: only length-1 arrays can be converted to Python scalars

使用numpy

In [178]: from numpy import *

In [179]: a=range(1242)

In [180]: b=np.cos(a)

In [181]: b
Out[181]: 
array([ 1.        ,  0.54030231, -0.41614684, ...,  0.35068442,
       -0.59855667, -0.99748752])

此外,numpy数组操作非常快:

In [182]: %timeit b=np.cos(a)  #numpy is the fastest
10000 loops, best of 3: 165 us per loop

In [183]: %timeit cos_ra = [math.cos(i) for i in a]
1000 loops, best of 3: 225 us per loop

In [184]: %timeit map(math.cos, a)
10000 loops, best of 3: 173 us per loop

问题是math.cos在试图传递列表时,希望获得一个数字作为参数。 您需要对每个列表元素调用math.cos

尝试使用map

map(math.cos, a)

相关问题 更多 >