# CalculusWithJulia' Euler Method for certain step size \$h\$ returns NaN

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]...);

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]...);

# 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``````

Just delete the `&& return NaN` and it solves my problem.