ordinary - 4 months ago 40

Python Question

I want to obtain results of cosine for each value.

`import numpy as np`

import math

t = np.arange(0, 20.5, 0.5)

print(math.cos(t))

I get 'TypeError: only length-1 arrays can be converted to Python scalars' error.

Answer

You want to apply the operation to every element of the array rather than to the entire array.

```
>>> import numpy as np
>>> import math
>>> t = np.arange(0, 20.5, 0.5)
>>> print([math.cos(element) for element in t])
[1.0, 0.8775825618903728, 0.5403023058681398, 0.0707372016677029, -0.4161468365471424, -0.8011436155469337, -0.9899924966004454, -0.9364566872907963, -0.6536436208636119, -0.2107957994307797, 0.28366218546322625, 0.70866977429126, 0.960170286650366, 0.9765876257280235, 0.7539022543433046, 0.3466353178350258, -0.14550003380861354, -0.6020119026848236, -0.9111302618846769, -0.9971721561963784, -0.8390715290764524, -0.4755369279959925, 0.004425697988050785, 0.4833047587530059, 0.8438539587324921, 0.9977982791785807, 0.9074467814501962, 0.594920663309892, 0.1367372182078336, -0.354924266788705, -0.7596879128588213, -0.9784534628188842, -0.9576594803233847, -0.7023970575027135, -0.27516333805159693, 0.2194399632114593, 0.6603167082440802, 0.939524893748256, 0.9887046181866692, 0.7958149698139441, 0.40808206181339196]
```

However the better solution is to use `np.cos`

which also accepts an array:

```
>>> np.cos(t)
array([ 1. , 0.87758256, 0.54030231, 0.0707372 , -0.41614684,
-0.80114362, -0.9899925 , -0.93645669, -0.65364362, -0.2107958 ,
0.28366219, 0.70866977, 0.96017029, 0.97658763, 0.75390225,
0.34663532, -0.14550003, -0.6020119 , -0.91113026, -0.99717216,
-0.83907153, -0.47553693, 0.0044257 , 0.48330476, 0.84385396,
0.99779828, 0.90744678, 0.59492066, 0.13673722, -0.35492427,
-0.75968791, -0.97845346, -0.95765948, -0.70239706, -0.27516334,
0.21943996, 0.66031671, 0.93952489, 0.98870462, 0.79581497,
0.40808206])
```

The second solution has huge benefits in terms of speed:

```
In [9]: %timeit [math.cos(element) for element in t]
The slowest run took 5.19 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.54 µs per loop
In [10]: %timeit np.cos(t)
The slowest run took 21.73 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.1 µs per loop
```