numpy向量化函数

向量化函数

自定义的 sinc 函数:

import numpy as np

def sinc(x):
    if x == 0.0:
        return 1.0
    else:
        w = np.pi * x
        return np.sin(w) / w

作用于单个数值:

sinc(0.0)

 

1.0

 

sinc(3.0)

 

3.8981718325193755e-17

但这个函数不能作用于数组:

 

x = np.array([1,2,3])
sinc(x)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-9d4f36f2aa7a> in <module>()
      1 x = np.array([1,2,3])
----> 2 sinc(x)

<ipython-input-1-dffe464e3332> in sinc(x)
      2 
      3 def sinc(x):
----> 4     if x == 0.0:
      5         return 1.0
      6     else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

可以使用 numpyvectorize 将函数 sinc 向量化,产生一个新的函数:

 

vsinc = np.vectorize(sinc)
vsinc(x)

 

array([  3.89817183e-17,  -3.89817183e-17,   3.89817183e-17])

其作用是为 x 中的每一个值调用 sinc 函数:

 

import matplotlib.pyplot as plt
%matplotlib inline

x = np.linspace(-5,5,101)
plt.plot(x, vsinc(x))

 

[<matplotlib.lines.Line2D at 0xa24e4e0>]

因为这样的用法涉及大量的函数调用,因此,向量化函数的效率并不高。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值