Anon Emouse - 4 months ago 19

Python Question

`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

`klist`

`xlist`

`K1`

`llist`

`1/2*k1*h`

`K2`

`klist`

`llist`

`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

`klist`

`0.84 + 0.5*-0.52*h`

I've tried doing

`[q + l for q, l in zip(llist, klist[1:])]`

`klist`

`[0.0], [0.84], [-0.52], etc...`

`klist[1:]`

`[]`

`yn+1`

Answer

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`