rk4_examples

Rk4_examples - r#More specific to a mechanical system in which velocity and position of an object are computed based on a particular force

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
# Two implimentations of the 4th order Runge-Kutta method which I found at the # DOSWA (Math, Physics, Programming) blog. # # Both these functions perform 1 rk4 step and return the updated values # so they need to be repeatedly called within another loop over time steps. #Very generic method def rk4(t0, h, s0, f): """RK4 implementation. t = current value of the independent variable h = amount to increase the independent variable (step size) s0 = initial state as a list. ex.: [initial_position, initial_velocity] f = function(state, t) to integrate""" r = range(len(s0)) s1 = s0 + [f(t0, s0)] s2 = [s0[i] + 0.5*s1[i+1]*h for i in r] s2 += [f(t0+0.5*h, s2)] s3 = [s0[i] + 0.5*s2[i+1]*h for i in r] s3 += [f(t0+0.5*h, s3)] s4 = [s0[i] + s3[i+1]*h for i in r] s4 += [f(t0+h, s4)] return t+h, [s0[i] + (s1[i+1] + 2*(s2[i+1]+s3[i+1]) + s4[i+1])*h/6.0 for i in
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: r] #More specific to a mechanical system in which velocity and position # of an object are computed based on a particular force field (acceleration) def rk4(x, v, a, dt): """Returns final (position, velocity) tuple after time dt has passed. x: initial position (number-like object) v: initial velocity (number-like object) a: acceleration function a(x,v,dt) (must be callable) dt: timestep (number)""" x1 = x v1 = v a1 = a(x1, v1, 0) x2 = x + 0.5*v1*dt v2 = v + 0.5*a1*dt a2 = a(x2, v2, dt/2.0) x3 = x + 0.5*v2*dt v3 = v + 0.5*a2*dt a3 = a(x3, v3, dt/2.0) x4 = x + v3*dt v4 = v + a3*dt a4 = a(x4, v4, dt) xf = x + (dt/6.0)*(v1 + 2*v2 + 2*v3 + v4) vf = v + (dt/6.0)*(a1 + 2*a2 + 2*a3 + a4) return xf, vf...
View Full Document

This note was uploaded on 10/05/2010 for the course PHYS phy503 taught by Professor Gladden during the Spring '09 term at Ole Miss.

Ask a homework question - tutors are online