4

I have this array named a of 1242 numbers. I need to get the cosine value for all the numbers in Python.

When I use : cos_ra = math.cos(a) I get an error stating:

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

How can I solve this problem??

Thanks in advance

2
  • 2
    Don't use numpy.math.cos, use numpy.cos. Commented Jan 10, 2014 at 11:59
  • ...because math.cos isn't vectorized, but np.cos is. (Also, better for performance since only one function call overhead) Commented Apr 29, 2020 at 2:56

5 Answers 5

6

Problem is you're using numpy.math.cos here, which expects you to pass a scalar. Use numpy.cos if you want to apply cos to an iterable.

In [30]: import numpy as np

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

Error:

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
Sign up to request clarification or add additional context in comments.

2 Comments

my reuptation is only at 11 as I joined stackexachange just now
@user1469380 Accepting an answer doesn't require any reputation ;-), but upvoting an answer does.
3

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

besides, numpy array operations are very fast:

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

Comments

3

The problem is that math.cos expect to get a number as argument while you are trying to pass a list. You need to call math.cos on each of the list elements.

Try using map :

map(math.cos, a)

Comments

2

Easy Way Motivated by the answer of zhangxaochen.

np.cos(np.arange(start, end, step))

Hope this helps!

Comments

1

math.cos() can only be called on individual values, not lists.

Another alternative, using list comprehension:

cos_ra = [math.cos(i) for i in a]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.