python-3.xdifferential-equationsverlet-integration

Python error, 'int' object is not subscriptable


I'm trying to solve differential equations using the Vertel algorithm, but I'm not able to rid myself of this error. Any suggestions?

def Vertel(dt, x0, v0, t, tstop, pravastrana, M=1):
    i = 0
    x = x0
    v = v0
    k  = 1     # Spring constant
    m  = 1 

    while t <= tstop:

    a = -(k/m)* x[i]

    if i == 0:
        v_next = v[i] + a* dt
        x_next = x[i] + v_next* dt
    else:
        x_next = 2* x[i] - x[i-1] + a* dt** dt
    x.append(x_next)
    t.append(t[i] + dt)
    i = i + 1
    t = t + dt
    return(x, t)

print(*Vertel(0.1 ,1 ,1 , 0, 10, pravastrana_1, ))

On the line, where I define a I get the error message:

> 'int' object is not subscriptable

Any help is appreciated, thank you


Solution

  • You want to initialize x and v as lists,

    x = [x0]
    v = [v0]
    

    To get the correct order of the Verlet algorithm you might also contemplate to initialize the first step one order higher, as

        v_next = v[i] + 0.5*a* dt
        x_next = x[i] + v_next* dt
    

    as that gives a correct Taylor expansion to the quadratic term. Note that the velocity is now correct for the half-step position, as it would be used in the Leapfrog Verlet variant.

    There will be problems that were masked by the first error, like the actual dual treatment of t as scalar variable and list at the same time, and probably more.