forked from Visualize-ML/Book3_Elements-of-Mathematics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBk3_Ch17_04.py
More file actions
132 lines (95 loc) · 3.5 KB
/
Bk3_Ch17_04.py
File metadata and controls
132 lines (95 loc) · 3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
###############
# Authored by Weisheng Jiang
# Book 4 | From Basic Arithmetic to Machine Learning
# Published and copyrighted by Tsinghua University Press
# Beijing, China, 2022
###############
# Bk3_Ch17_04.py
import numpy as np
import matplotlib.pyplot as plt
from sympy.abc import x
from sympy import latex, lambdify, diff, sin, log, exp
def num_diff(f,a,method,dx):
# f: function handle
# a: expansion point
# method: 'forward', 'backward', and 'central'
# dx: step size
if method == 'central':
return (f(a + dx) - f(a - dx))/(2*dx)
elif method == 'forward':
return (f(a + dx) - f(a))/dx
elif method == 'backward':
return (f(a) - f(a - dx))/dx
else:
raise ValueError("Method must be 'central', 'forward' or 'backward'.")
f_x = exp(-x**2)
x_array = np.linspace(-3,3,100)
a_array = np.linspace(-2.5,2.5,11)
f_x_fcn = lambdify(x,f_x)
f_x_array = f_x_fcn(x_array)
f_x_1_diff = diff(f_x,x)
f_x_1_diff_fcn = lambdify(x,f_x_1_diff)
f_x_1_diff_array = f_x_1_diff_fcn(x_array)
#%% visualization
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(2, 1, 1)
ax.plot(x_array, f_x_array, '#0070C0', linewidth = 1.5)
ax.set_ylim(np.floor(f_x_array.min()),
np.ceil(f_x_array.max()))
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_xlim((x_array.min(),x_array.max()))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax = fig.add_subplot(2, 1, 2)
ax.plot(x_array, f_x_1_diff_array, '#0070C0', linewidth = 1.5)
ax.set_xlabel('x')
ax.set_ylabel('f\'(x)')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_xlim((x_array.min(),x_array.max()))
#%% numerical methods
dx = 0.2
diff_central = num_diff(f_x_fcn,a_array,'central', dx)
diff_forward = num_diff(f_x_fcn,a_array,'forward', dx)
diff_backward = num_diff(f_x_fcn,a_array,'backward',dx)
fig, ax = plt.subplots()
ax.plot(x_array, f_x_1_diff_array, '#0070C0', linewidth = 1.5)
ax.plot(a_array, diff_central, marker = '.',
markersize = 12, linestyle = 'none',
label = 'central')
ax.plot(a_array, diff_forward, marker = '>',
markersize = 12, linestyle = 'none',
label = 'forward')
ax.plot(a_array, diff_backward, marker = '<',
markersize = 12, linestyle = 'none',
label = 'backward')
ax.set_xlabel('x')
ax.set_ylabel('f\'(x)')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_xlim((x_array.min(),x_array.max()))
plt.axhline(y=0, color='k', linestyle='--', linewidth = 0.25)
plt.legend()
#%% varying step size
dx_array = np.linspace(0.01,0.2,20)
a = 1
diff_central = num_diff(f_x_fcn,a,'central', dx_array)
diff_forward = num_diff(f_x_fcn,a,'forward', dx_array)
diff_backward = num_diff(f_x_fcn,a,'backward',dx_array)
f_x_1_diff_a = f_x_1_diff_fcn(a)
fig, ax = plt.subplots()
ax.plot(dx_array, diff_central, linewidth = 1.5,
marker = '.',label = 'central')
ax.plot(dx_array, diff_forward, linewidth = 1.5,
marker = '>',label = 'forward')
ax.plot(dx_array, diff_backward, linewidth = 1.5,
marker = '<',label = 'backward')
plt.axhline(y=f_x_1_diff_a, color='k', linestyle='--',
linewidth = 0.25,label = 'analytical')
ax.set_xlim((dx_array.min(),dx_array.max()))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.legend()
ax.set_xlabel('\u0394x')
ax.set_ylabel('f\'(x)')