python导入数学库_Python中的数学库和数组

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?

解决方案

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

你可能感兴趣的:(python导入数学库)