$$x_{k+1} = g(x_k)$$ * That is: guess $x_0$. * Evaluate $g(x_0)$. * The result is $x_1$. * Repeat.
Geometrically $x_{k+1} = g(x_k)$ finds the intersection of the $y=g(x)$ and $y=x$ lines.
using Plots
using LaTeXStrings
x = LinRange(-2,3,100)
y1 = x.^2 .- 2.0
y2 = 1.0 .+ 2.0./x
y3 = (x .+ 2.).^0.5
y4 = (x.^2 .+ 2)./(2.0*x .- 1)
Plots.resetfontsizes(); Plots.scalefontsizes(1.3)
plot( x,y1,label=L"x^2-2", lw=2)
plot!(x,y2,label=L"1+2/x", lw=2)
plot!(x,y3,label=L"(x+2)^{1/2}", lw=2)
plot!(x,y4,label=L"(x^2+2)/(2x-1)", lw=2)
plot!(x,x, label=L"x", linestyle=:dash, color="black")
plot!(foreground_color_legend=nothing)
plot!(xlim=[1,3], ylim=[-1,8], xlabel="x", ylabel="g(x)")
using LinearAlgebra
function FP(g, x, tol=1E-5, maxit=1000)
for niter in 1:maxit+1
xnew = g(x)
if norm(xnew-x)/norm(x) <= tol
return xnew, niter
end
x = xnew
end
println("warning, reached maxit = $maxit")
return x, niter
end
#-----------
g(x) = √(x+2)
#-----------
xguess = 4.0
x, nit = FP(g, xguess)
println("x, nit = $x, $nit")
x, nit = 2.000006616131052, 9
Equations:
$$ Re = \frac{\rho Dv}{\mu}.$$$$ \frac{1}{\sqrt{f}} = -\log_{10}\left(\frac{\epsilon/D}{3.7} + \frac{2.51}{Re\sqrt{f}}\right),$$$$ \frac{\Delta P}{\rho} = \frac{fLv^2}{2D} \rightarrow v = \sqrt{\frac{2D\Delta P}{\rho f L}}.$$Approach:
Note, this calls FP
from example 1
using PyFormattedStrings
function g_fluids(vfhat)
v = vfhat[1]
fhat = vfhat[2]
ρ = 1000. # kg/m3
μ = 1E-3 # Pa*s = kg/m*s
D = 0.1 # m
L = 100. # m
ϵ = D/100. # m
ΔP = 101325. # Pa
Re = ρ*D*v/μ
fhat = -log10(ϵ/D/3.7 + 2.51*fhat/Re)
v = √(2*D*ΔP/ρ/L)*fhat
return [v, fhat]
end
#-------------------
vfhat_g = [1.0, 0.1]
vfhat, nit = FP(g_fluids, vfhat_g)
println(f"v = {vfhat[1]:.4f} (m/s)")
println(f"f = {1/vfhat[2]^2:.4f}")
println(f"# iterations = {nit}")
v = 1.1521 (m/s) f = 0.1527 # iterations = 3
x = 1
println(f"x = {x:.15f}")
for k in 1:6
x = x - (x^2 - π^2)/(2.0*x)
println(f"x = {x:.15f}")
end
x = 1.000000000000000 x = 5.434802200544679 x = 3.625401431921964 x = 3.173874724746142 x = 3.141756827069927 x = 3.141592657879261 x = 3.141592653589793