Modified midpoint method for solving the initial v

From , 5 Years ago, written in Python, viewed 181 times.
URL https://pastebin.vip/view/60bb8062
  1. ''' yStop = integrate (F,x,y,xStop,tol=1.0e-6)
  2.    Modified midpoint method for solving the
  3.    initial value problem y' = F(x,y}.
  4.    x,y   = initial conditions
  5.    xStop = terminal value of x
  6.    yStop = y(xStop)
  7.    F     = user-supplied function that returns the
  8.            array F(x,y) = {y'[0],y'[1],...,y'[n-1]}.
  9. '''
  10. from numpy import zeros,float,sum
  11. from math import sqrt
  12.  
  13. def integrate(F,x,y,xStop,tol):
  14.  
  15.     def midpoint(F,x,y,xStop,nSteps):
  16.   # Midpoint formulas
  17.         h = (xStop - x)/nSteps
  18.         y0 = y
  19.         y1 = y0 + h*F(x,y0)
  20.         for i in range(nSteps-1):
  21.             x = x + h
  22.             y2 = y0 + 2.0*h*F(x,y1)
  23.             y0 = y1
  24.             y1 = y2
  25.         return 0.5*(y1 + y0 + h*F(x,y2))
  26.  
  27.     def richardson(r,k):
  28.   # Richardson's extrapolation      
  29.         for j in range(k-1,0,-1):
  30.             const = (k/(k - 1.0))**(2.0*(k-j))
  31.             r[j] = (const*r[j+1] - r[j])/(const - 1.0)
  32.         return
  33.  
  34.     kMax = 51
  35.     n = len(y)
  36.     r = zeros((kMax,n),dtype=float)
  37.   # Start with two integration steps
  38.     nSteps = 2
  39.     r[1] = midpoint(F,x,y,xStop,nSteps)
  40.     r_old = r[1].copy()
  41.   # Increase the number of integration points by 2
  42.   # and refine result by Richardson extrapolation
  43.     for k in range(2,kMax):
  44.         nSteps = 2*k
  45.         r[k] = midpoint(F,x,y,xStop,nSteps)
  46.         richardson(r,k)
  47.       # Compute RMS change in solution
  48.         e = sqrt(sum((r[1] - r_old)**2)/n)
  49.       # Check for convergence
  50.         if e < tol: return r[1]
  51.         r_old = r[1].copy()
  52.     print "Midpoint method did not converge"
  53. #//python/7412

Reply to "Modified midpoint method for solving the initial v"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website