Math library and arrays in Python

ⅰ亾dé卋堺 提交于 2019-12-11 09:47:15

问题


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.



来源:https://stackoverflow.com/questions/46593021/math-library-and-arrays-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!