Problem Parameters: The function that you build needs to take in
- The current value of the independent variable (x)
- The current values of the dependent variables (y) <-- (list)
- The step-size of the independent variable (h)
- The function which calculates the derivatives depending on x and y. <-- will return a list
The function will return the values of the dependent variables (y) at x+h
We are given a tester code and when mine runs I'm getting the "list index out of range" error
My code is:
def rk4( x, y, h, derivs ):
# ... Note, y is a list, ynew is a list, derivs returns a list of derivatives
n = len( y )
k1 = derivs( x, y )
ym = [ ]
ye = [ ]
slope = [ ]
ynew = [ ]
for i in range( n ):
ym[ i ] = y[ i ] + k1[ i ] * h / 2
return ym
k2 = derivs( (x + h / 2), ym )
for i in range( n ):
ym[ i ] = y[ i ] + k2[ i ] * h / 2
return ym
k3 = derivs( (x + h / 2), ym )
for i in range( n ):
ye.append( y[ i ] + k3[ i ] * h )
return ye
k4 = derivs( (x + h), ye )
for i in range( n ):
slope.append( (k1[ i ] + 2 * (k2[ i ] + k3[ i ]) + k4[ i ]) / 6 )
ynew.append( y[ i ] + slope[ i ] * h )
return ynew
x = x + h
return ynew
Tester Code:
if __name__ == '__main__':
# This is a spring/mass/damper system.
# The system oscillates and the oscillations should become smaller over time for positive stiffness and damping values
stiffness = 4; #
damping = 0.5;
def derivs(t, y):
return [y[1], -stiffness * y[0] - damping * y[1]]
y = [1, 4]
n = 50
tlow = 0
thigh = 10
h = (thigh - tlow) / (n - 1)
for ii in range ( n ):
t = tlow + ii * h
y = rk4 ( t, y, h, derivs )