mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-09 21:36:27 +08:00
111 lines
14 KiB
Markdown
111 lines
14 KiB
Markdown
# 向量化函数
|
||
|
||
自定义的 `sinc` 函数:
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
import numpy as np
|
||
|
||
def sinc(x):
|
||
if x == 0.0:
|
||
return 1.0
|
||
else:
|
||
w = np.pi * x
|
||
return np.sin(w) / w
|
||
|
||
```
|
||
|
||
作用于单个数值:
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
sinc(0.0)
|
||
|
||
```
|
||
|
||
Out[2]:
|
||
|
||
```py
|
||
1.0
|
||
```
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
sinc(3.0)
|
||
|
||
```
|
||
|
||
Out[3]:
|
||
|
||
```py
|
||
3.8981718325193755e-17
|
||
```
|
||
|
||
但这个函数不能作用于数组:
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
x = np.array([1,2,3])
|
||
sinc(x)
|
||
|
||
```
|
||
|
||
```py
|
||
---------------------------------------------------------------------------
|
||
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()
|
||
```
|
||
|
||
可以使用 `numpy` 的 `vectorize` 将函数 `sinc` 向量化,产生一个新的函数:
|
||
|
||
In [5]:
|
||
|
||
```py
|
||
vsinc = np.vectorize(sinc)
|
||
vsinc(x)
|
||
|
||
```
|
||
|
||
Out[5]:
|
||
|
||
```py
|
||
array([ 3.89817183e-17, -3.89817183e-17, 3.89817183e-17])
|
||
```
|
||
|
||
其作用是为 `x` 中的每一个值调用 `sinc` 函数:
|
||
|
||
In [6]:
|
||
|
||
```py
|
||
import matplotlib.pyplot as plt
|
||
%matplotlib inline
|
||
|
||
x = np.linspace(-5,5,101)
|
||
plt.plot(x, vsinc(x))
|
||
|
||
```
|
||
|
||
Out[6]:
|
||
|
||
```py
|
||
[<matplotlib.lines.Line2D at 0xa24e4e0>]
|
||
```
|
||
|
||

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