math - what will be python code for runge kutta second method? -
is code ok?
def rkn(x, fx, n, hs): k1 = [] k2 = [] k3 = [] k4 = [] xk = [] in range(n): k1.append(fx[i](x)*hs) in range(n): xk.append(x[i] + k1[i]*0.5) in range(n): k2.append(fx[i](xk)*hs) in range(n): xk[i] = x[i] + k2[i]*0.5 in range(n): k3.append(fx[i](xk)*hs) in range(n): xk[i] = x[i] + k3[i] in range(n): k4.append(fx[i](xk)*hs) in range(n): x[i] = x[i] + (k1[i] + 2*(k2[i] + k3[i]) + k4[i])/6 return x
with numpy
seems more readable:
code taken http://www.math-cs.gordon.edu/courses/mat342/python/diffeq.py
def rk2a( f, x0, t ): """second-order runge-kutta method solve x' = f(x,t) x(t[0]) = x0. usage: x = rk2a(f, x0, t) input: f - function of x , t equal dx/dt. x may multivalued, in case should list or numpy array. in case f must return numpy array same dimension x. x0 - initial condition(s). specifies value of x when t = t[0]. can either scalar or list or numpy array if system of equations being solved. t - list or numpy array of t values compute solution at. t[0] the initial condition point, , difference h=t[i+1]-t[i] determines step size h. output: x - numpy array containing solution values corresponding each entry in t array. if system being solved, x array of arrays. notes: version based on algorithm presented in "numerical analysis", 6th edition, burden , faires, brooks-cole, 1997. """ n = len( t ) x = numpy.array( [ x0 ] * n ) in xrange( n - 1 ): h = t[i+1] - t[i] k1 = h * f( x[i], t[i] ) / 2.0 x[i+1] = x[i] + h * f( x[i] + k1, t[i] + h / 2.0 ) return x
Comments
Post a Comment