用電腦算微分

$$f’(\pi) = \lim_{h\to 0} \frac{(\pi+h)^2-\pi^2}{h}.$$

h = range(0, 0.01, length=11); h = h[11: -1 : 2];
fp = ((pi.+h).^2 .- pi^2)./h;
hcat(h, fp, fp.-2*pi)


$h$ $f'$ $f’-2\pi$
0.01 6.29319 0.01
0.009 6.29219 0.009
0.008 6.29119 0.008
0.007 6.29019 0.007
0.006 6.28919 0.006
0.005 6.28819 0.005
0.004 6.28719 0.004
0.003 6.28619 0.003
0.002 6.28519 0.002
0.001 6.28419 0.001

Question: 用數值計算微分能有多精確? 這個誤差能不能一直遞減下去?

h = range(1, 16, length=16); h = 10.0.^(-h[1: 16]);
fp = ((pi.+h).^2 .- pi^2)./h;
hcat(h, fp, abs.(fp.-2*pi))


$h$ $f'$ $abs(f’-2\pi)$
0.1 6.38319 0.1
0.01 6.29319 0.01
0.001 6.28419 0.001
0.0001 6.28329 0.0001
1.0e-5 6.2832 9.99998e-6
1.0e-6 6.28319 1.00006e-6
1.0e-7 6.28319 9.5898e-8
1.0e-8 6.28319 4.26073e-8
1.0e-9 6.28319 2.20243e-7
1.0e-10 6.28319 1.9966e-6
1.0e-11 6.28315 3.35305e-5
1.0e-12 6.28297 0.000211166
1.0e-13 6.27054 0.0126457
1.0e-14 6.39488 0.111699
1.0e-15 5.32907 0.954115
1.0e-16 0.0 6.28319

using Plots
plot(log10.(h), log10.(abs.(fp.-2*pi)),label="Error")
xlabel!("log10(h)")
ylabel!("log10(Error)")


Summary:

• 我們可以用數值計算來估計一個函數在某點的微分值 $$f’(a) \approx \frac{f(a+h)-f(a)}{h}.$$ 這樣的做法稱為有限差分法 (finite difference method).

• 不過計算時 $h$ 值不能無限取小, 需考慮到捨入誤差的影響.

Te-Sheng Lin (林得勝)
Associate Professor

The focus of my research is concerned with the development of analytical and computational tools, and further to communicate with scientists from other disciplines to solve engineering problems in practice.