Guest User

Untitled

a guest
Oct 15th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. struct Problem
  2. # u'' = -g*u + s
  3. g
  4. s
  5. tstops
  6. end
  7.  
  8. mutable struct Cache
  9. u
  10. uprev
  11. t
  12. tprev
  13. tnext
  14. h # stepwidth
  15. step # current step
  16. sol # array of solutions
  17. end
  18.  
  19.  
  20. function solve(prob,u0,du0)
  21.  
  22. cache = Cache(undef,undef,undef,undef,undef,undef,undef,undef)
  23. initialize(prob,cache,u0,du0)
  24.  
  25. for t in 3:length(prob.tstops)
  26. perform_step(prob,cache)
  27. end
  28.  
  29. return cache
  30.  
  31. end
  32.  
  33. function initialize(prob,cache,u0,du0)
  34. cache.sol = Array{Float64}(undef,length(prob.tstops))
  35. cache.tprev = prob.tstops[1]
  36. cache.t = prob.tstops[2]
  37. cache.tnext = prob.tstops[3]
  38. cache.h = cache.t-cache.tprev
  39. cache.u = u0 +
  40. du0*cache.h +
  41. cache.h^2 / 2 * (-prob.g(cache.tprev)*u0 + prob.s(cache.tprev)) +
  42. cache.h^3 /6 * (-prob.g(cache.tprev) )
  43.  
  44. cache.uprev = u0
  45. cache.sol[1] = cache.uprev
  46. cache.sol[2] = cache.u
  47. cache.step = 3
  48. end
  49.  
  50. function perform_step(prob,cache)
  51. u = cache.u
  52. uprev = cache.uprev
  53.  
  54. t = cache.t
  55. tprev = cache.tprev
  56. tnext = cache.tnext
  57.  
  58. g = prob.g(t)
  59. gnext = prob.g(tnext)
  60. gprev = prob.g(tprev)
  61.  
  62. s = prob.s(t)
  63. snext = prob.s(tnext)
  64. sprev = prob.s(tprev)
  65.  
  66. h = cache.h
  67.  
  68. unext = (2*u*(1-(5*h^2*g)/12) -
  69. uprev*(1+(h^2*gprev)/12) +
  70. h^2/12*(snext+10*s+sprev))/
  71. (1+h^2/12*gnext)
  72.  
  73. cache.uprev = cache.u
  74. cache.u = unext
  75. cache.sol[cache.step]=unext
  76.  
  77.  
  78. cache.step = cache.step+1
  79. step = cache.step
  80.  
  81. if step >= length(prob.tstops)
  82. return
  83. end
  84. cache.tprev = t
  85. cache.t = tnext
  86. cache.tnext = prob.tstops[step]
  87. end
  88.  
  89.  
  90. function main(g,s)
  91. #u'' = -gu + s
  92. #
  93. #g = 1
  94. #s = 8
  95. tstops = 0:0.0001:10
  96. prob = Problem(x->g,x->s,tstops)
  97. @time sol = solve(prob,0,0)
  98. unicodeplots()
  99. y = (broadcast(cos,prob.tstops.*sqrt(g)).-1) .*(-s/g)
  100. plot(prob.tstops,sol.sol)
  101. plot!(prob.tstops,y)
  102. xlims!(prob.tstops[1],prob.tstops[end])
  103. gui()
  104. end
  105.  
  106. main(rand(2)...)
Add Comment
Please, Sign In to add comment