from math import sin
def euler(f, x0, t0, h, N):
t = t0
x = x0
while t <= N:
t += h
x += [h * x for x in f(t, x)]
print(x)
def f(t, x):
vv = [-x[0]**3 - x[0] + sin(t)]
return vv
This is my code. f
is a function, x0
is the initial condition at time t0
, t0
is the initial time, h
is the stepsize, and N
is the number of steps. When I enter >>>euler(f, [0.], 0., 1., 10)
I get [0.0, 0.8414709848078965, 0.9092974268256817, 0.1411200080598672, -0.7568024953079282, -0.9589242746631385, -0.27941549819892586, 0.6569865987187891, 0.9893582466233818, 0.4121184852417566, -0.5440211108893698]
Which is incorrect.
I know my list comprehension statement is missing something, but I can't really pinpoint what I'm missing because I don't know how it is returning those values. The first 2 values are correct, then after that, it incorrectly calculates the remaining values.
When I am supposed to get
0.0
0.8414709848078965
0.313474190234726
0.11031613198378529
-0.758145003910546
-0.5231547727660838
-0.1362327890906342
0.6595149938422956
0.7024955870270317
0.06543687806493725
using this code:
from math import sin
def euler(f, x0, t0, h, N):
t = t0
x = x0
while t <= N:
t += h
x += h * f(t,x)
print(t,x)
def f(t, x):
vv = -x**3 - x + sin(t)
return vv