Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # I am drawing a plot in order to review work done by a student. I'm a TA.
- using Plots
- pyplot()
- function cbweb(g::Function,x0::Float64,maxit::Int,tol::Float64,
- a::Float64,b::Float64,figname::String)
- # EXAMPLE :
- # g(x) = 1-x^2
- # (x, numit, fail) = fixedpoint(g,0.5,10,1.0e-4)
- #
- r = a:0.01:b
- plot(g, r, label="g")
- ylims!((a, b))
- diagonal(x) = x
- plot!(diagonal, r, label="")
- println("running a fixed-point iteration ...")
- strit = @sprintf("%3d", 0)
- strx0 = @sprintf("%.4e", x0)
- println("$strit : $strx0")
- xprevious = x0
- xnext = xprevious
- for i=1:maxit
- xnext = g(xprevious)
- if i == 1
- plot!([xprevious], [xnext], line=(:sticks, :black), label="")
- else
- if xprevious < xnext
- plot!([xprevious], xprevious:0.01:xnext, line=(:black), label="")
- else
- plot!([xprevious], xnext:0.01:xprevious, line=(:black), label="")
- end
- end
- if xprevious < xnext
- plot!(xprevious:0.01:xnext, [xnext], line=(:black), label="")
- else
- plot!(xnext:0.01:xprevious, [xnext], line=(:black), label="")
- end
- strit = @sprintf("%3d", i)
- strxi = @sprintf("%.4e", xnext)
- error = abs(xnext - xprevious)
- strerr = @sprintf("%.2e", error)
- println("$strit : $strxi : $strerr" )
- if error < tol
- savefig(figname)
- return (xnext, i, false)
- end
- xprevious = xnext
- end
- savefig(figname)
- return (xnext, maxit, true)
- end
- function main()
- # Calls the fixed point iteration.
- x0 = 0.5
- maxit = 15
- tol = 1.0e-8
- g(x) = 2*sin(x)
- (endpt, numit, fail) = cbweb(g, x0, maxit, tol, 0.0, 2.1, "cobweb4")
- end
- main()
- gui()
Add Comment
Please, Sign In to add comment