FiniteDifferences
Copyright By PowCoder代写 加微信 powcoder
using Plots
# Example 1
f(x) = 1 + x + x^2
h = 2.0^(-S)
(f(x + h) – f(x))/h # True answer: 1, for h small, its exact!
h = 2.0^(-60)
(f(x + h) – f(x))/h # True answer: 1, for h small, its wrong!
h = 2.0 .^ (-(0:55))
abs_err_f = abs.((f.(h) .- f(0)) ./ h .- 1)
56-element Vector{Float64}:
0.00390625
0.001953125
0.0009765625
0.00048828125
0.000244140625
h = 0.000000000001
(f(x + h) – f(x))/h # True answer: 1, for h small, starts to converge, but then diverges!
1.000088900582341
# Example 2
g(x) = 1 + x/3 + x^2
h = 2.0^(-25)
(g(x + h) – g(x))/h # True answer: 1, for h small, starts to converge, but then diverges!
0.3333333656191826
h = 10.0 .^ (-(0:20))
abs_err_f = abs.((f.(h) .- f(0)) ./ h .- 1)
abs_err_g = abs.((g.(h) .- g(0)) ./ h .- 1/3)
plot(abs_err_f; yscale=:log10, label=”f”)
plot!(abs_err_g; yscale=:log10, label=”g”)
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com