Math library and arrays in Python

2019-08-03 07:27发布

问题:

I am to use the Math Library to do some calculations on an array.
I tried something like this:

import numpy as np
import math
a = np.array([0, 1, 2, 3])
a1 = np.vectorize(a)
print("sin(a) = \n", math.sin(a1)) 

Unfortunately it does not work. An error occur: "TypeError: must be real number, not vectorize".

How can I use the vectorize function to be able to calculate that kind of things?

回答1:

The whole point of numpy is that you don't need any math method or any list comprehension:

>>> import numpy as np
>>> a = np.array([0, 1, 2, 3])
>>> a + 1
array([1, 2, 3, 4])
>>> np.sin(a)
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001])
>>> a ** 2
array([0, 1, 4, 9])
>>> np.exp(a)
array([  1.        ,   2.71828183,   7.3890561 ,  20.08553692])

You can use a as if it were a scalar and you get the corresponding array.

If you really need to use math.sin (hint: you don't), you can vectorize it (the function itself, not the array):

>>> vsin = np.vectorize(math.sin)
>>> vsin(a)
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001])


回答2:

import numpy as np
import math
a = np.array([0, 1, 2, 3])
print("sin(a) = \n", [math.sin(x) for x in a])

math.sin requires one real number at a time.