0

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

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
Nitaa a
  • 121
  • 4
  • You are trying to subscript the integers you are passing, `v[i]` and `x[i]` are not valid operations on integers 1 and 1 you pass onto `vertel` – Bijay Regmi Mar 28 '21 at 19:19
  • When posting Python questions, please make sure that the indentation in your question matches your code. The code you have posted is unrunnable. – David Buck Mar 28 '21 at 19:32
  • As it were only the first and last line that were shifted to hack the indented code markup, this was easy to repair with code fences. The code will still not run without changes to a significant number of its lines. – Lutz Lehmann Mar 28 '21 at 19:39

1 Answers1

1

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.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
  • Great, thank you very much! Yes there still is some work. Right thing to do is: define ts = [t], then instead of t.append(t[i] + dt) do ts.append(t). Higher order in the first step is probrably the way to go. – Nitaa a Mar 29 '21 at 08:57
  • Or, for uniformity of the variable scheme, pass the parameter as `t0`, set `t=[t0]` and then use `t[i]` or `t[-1]` whenever accessing the recent time. – Lutz Lehmann Mar 29 '21 at 09:02