Good day all,
For simple y'=y
Why is the Euler computation returns NaN
for h=0.1 , and several other h values?
Take a look at the Pretty Tables below.
This is my code:
using SymPy, CalculusWithJulia, LaTeXStrings,Plots,PrettyTables
@syms x,y, u()
function linterp(xs, ys)
function(x)
((x < xs[1]) || (x > xs[end])) && return NaN
for i in 1:(length(xs) - 1)
if xs[i] <= x < xs[i+1]
l = (x-xs[i]) / (xs[i+1] - xs[i])
return (1-l) * ys[i] + l * ys[i+1]
end
end
ys[end]
end
end
F(y,x) = y
x0,y0 = 0,1
function euler(F, x0, xn, y0, n)
h = (xn - x0)/n
xs = zeros(n+1)
ys = zeros(n+1)
xs[1] = x0
ys[1] = y0
for i in 1:n
xs[i + 1] = xs[i] + h
ys[i + 1] = ys[i] + h * F(ys[i], xs[i])
end
linterp(xs, ys)
end
π(y,x) = y
π0, πn, π0 = 0, 1, 1
f1 = euler(π, π0, πn, π0, 5)
f2 = euler(π, π0, πn, π0, 10)
f3 = euler(π, π0, πn, π0, 20)
f4 = euler(π, π0, πn, π0, 100)
f5 = euler(π, π0, πn, π0, 200)
#f1(πn)
println("Euler's Method:")
println("The differential equation: y' = y")
println("Initial condition: y(0) = 1")
println("interval [0,1]")
println("")
println("Exact solution:")
# To calculate the analytic solution
D = Differential(x)
dsolve(D(u)(x) - F(u(x), x))
out = dsolve(D(u)(x) - F(u(x),x), u(x), ics=Dict(u(x0) => y0))
sympy.pretty_print(rhs(out))
println("")
println(pretty_table(String,
vcat([[(y0-x0)/j euler(π, π0, πn, π0,j)( πn) exp(πn) abs(euler(π, π0, πn, π0,j)( πn)-exp((y0-x0)/j+1)) ] for j in 5:5:50]...);
header=["h", "y_{n}", "e^{x_{n}}", "error=Exact-Estimate"]))
println(pretty_table(String,
vcat([[(y0-x0)/j euler(π, π0, πn, π0,j)( πn) exp(πn) abs(euler(π, π0, πn, π0,j)( πn)-exp((y0-x0)/j+1)) ] for j in 100:100:200]...);
header=["h", "y_{n}", "e^{x_{n}}", "error=Exact-Estimate"]))
# To plot
p = plot(legend=:bottomright)
vectorfieldplot!((x,y) -> [1, F(x,y)], xlims=(0, 1.1), ylims=(0.5, 3))
plot!(rhs(out), linecolor=:green, linewidth=2, label=L"e^{x_{n}}")
plot!(f1, π0, πn, linecolor=:orange, linewidth=2, label=L"y_{n} \ h = 0.2")
plot!(f2, π0, πn, linecolor=:red3, linewidth=2, label=L"y_{n} \ h = 0.1")
plot!(f3, π0, πn, linecolor=:red1, linewidth=2, label=L"y_{n} \ h = 0.05")
plot!(f4, π0, πn, linecolor=:blue2, linewidth=2, label=L"y_{n} \ h = 0.01")
plot!(f5, π0, πn, linecolor=:purple, linewidth=2, label=L"y_{n} \ h = 0.005")
```ok