Python中的数学库和数组 [英] Math library and arrays in Python

查看:69
本文介绍了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)) 

不幸的是,它不起作用.发生错误:"TypeError: must be real number, not vectorize".

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

您可以像使用标量一样使用a并获得相应的数组.

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

如果您确实需要使用math.sin(提示:不需要),则可以

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中的数学库和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆