Guest User

Untitled

a guest
Jun 24th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. # I am drawing a plot in order to review work done by a student. I'm a TA.
  2.  
  3. using Plots
  4. pyplot()
  5.  
  6. function cbweb(g::Function,x0::Float64,maxit::Int,tol::Float64,
  7. a::Float64,b::Float64,figname::String)
  8.  
  9. # EXAMPLE :
  10. # g(x) = 1-x^2
  11. # (x, numit, fail) = fixedpoint(g,0.5,10,1.0e-4)
  12. #
  13. r = a:0.01:b
  14. plot(g, r, label="g")
  15. ylims!((a, b))
  16. diagonal(x) = x
  17. plot!(diagonal, r, label="")
  18. println("running a fixed-point iteration ...")
  19. strit = @sprintf("%3d", 0)
  20. strx0 = @sprintf("%.4e", x0)
  21. println("$strit : $strx0")
  22. xprevious = x0
  23. xnext = xprevious
  24. for i=1:maxit
  25. xnext = g(xprevious)
  26. if i == 1
  27. plot!([xprevious], [xnext], line=(:sticks, :black), label="")
  28. else
  29. if xprevious < xnext
  30. plot!([xprevious], xprevious:0.01:xnext, line=(:black), label="")
  31. else
  32. plot!([xprevious], xnext:0.01:xprevious, line=(:black), label="")
  33. end
  34. end
  35. if xprevious < xnext
  36. plot!(xprevious:0.01:xnext, [xnext], line=(:black), label="")
  37. else
  38. plot!(xnext:0.01:xprevious, [xnext], line=(:black), label="")
  39. end
  40. strit = @sprintf("%3d", i)
  41. strxi = @sprintf("%.4e", xnext)
  42. error = abs(xnext - xprevious)
  43. strerr = @sprintf("%.2e", error)
  44. println("$strit : $strxi : $strerr" )
  45. if error < tol
  46. savefig(figname)
  47. return (xnext, i, false)
  48. end
  49. xprevious = xnext
  50. end
  51. savefig(figname)
  52. return (xnext, maxit, true)
  53. end
  54.  
  55. function main()
  56. # Calls the fixed point iteration.
  57. x0 = 0.5
  58. maxit = 15
  59. tol = 1.0e-8
  60. g(x) = 2*sin(x)
  61. (endpt, numit, fail) = cbweb(g, x0, maxit, tol, 0.0, 2.1, "cobweb4")
  62. end
  63.  
  64. main()
  65.  
  66. gui()
Add Comment
Please, Sign In to add comment