Anon Emouse Anon Emouse - 9 months ago 29
Python Question

Accessing previous element for the Runge-Kutta 2nd order

from math import sin
def rk(f,x0,t0,h,N):
t = t0
xlist = x0
while t < N*h:
klist = f(t,xlist) #GIVES ME K1
xlist = [x+h *k for x,k in zip(xlist, klist)]

llist = [u * 0.5*h for u in klist] #GIVES ME 1/2 Y1
t += h

The midpoint method (Runge-Kutta 2nd order) the equation goes like this:

K1 = f(t, x)
K2 = f(t0 + 1/2*h, x0 + 1/2*K1*h)
yn+1 = yn + k2*h

So far, my
combined with the
give me
, My
gives me the
portion of the
equation. I'm having trouble accessing the previous element in
to be able to add that element to my
. So for example

print (klist, llist)
[0.0] [0.0]
[0.84] [0.42]
[-0.52] [-0.026]

And I want to add the previous element of the
per midpoint method to the 1/2*k1*h. so it would look like
0.84 + 0.5*-0.52*h

I've tried doing
[q + l for q, l in zip(llist, klist[1:])]
but it doesn't work since my
[0.0], [0.84], [-0.52], etc...
and so
would just return
. So how would go about this? I tried making a list of lists, but when it came to adding the values, I would just get an error since I can't add a float to the list. Also for the
equation, how would I add those since they would also be different types ?

Answer Source

The method reads, including an intermediate state, as

k1 = f(t, x)
xm = x + 0.5*h*k1
k2 = f(t + 0.5*h, xm)
x  = x + h*k2

which should be list-ified as

k1list = f(t, xlist)
xmlist = [ x + 0.5*h*k1 for x,k1 in zip(xlist,k1list)]
k2list = f(t + 0.5*h, xmlist)
xlist  = [ x + h*k2 for x,k1 in zip(xlist,k2list)]

As told previously multiple times, the + operator applied to lists in python is not element-wise addition but list concatenation. If you want to use vector arithmetic you have to use a dedicated vector class such as numpy.array