Explicit Euler method doesn't behave how I expect - python

I have implemented the following explicit euler method in python:
def explicit_euler(df, x0, h, N):
"""Solves an ODE IVP using the Explicit Euler method.
Keyword arguments:
df - The derivative of the system you wish to solve.
x0 - The initial value of the system you wish to solve.
h - The step size.
N - The number off steps.
"""
x = np.zeros(N)
x[0] = x0
for i in range(0, N-1):
x[i+1] = x[i] + h * df(x[i])
return x
Following the article on wikipedia I can plot the function and verify that I get the same plot: . I believe that here the method I have written is working correctly.
Next I tried to use it to solve the last system given on this page and instead of the plot shown there I obtain this:
I am not sure why my plot doesn't match the one shown on the webpage. The explicit euler method seems to work fine when I use it to solve systems where the slope doesn't change, but for an oscillating function it never seems to mimic it at all. Not even showing the expected error gain as indicated on the linked webpage. I am not sure what is wrong with the method I have implemented.
Here is the code used for plotting and the derivative:
def g(t):
return -0.5 * np.exp(t * 0.5) * np.sin(5 * t) + 5 * np.exp(t * 0.5)
* np.cos(5 * t)
h = 0.001
x0 = 0
tn = 4
N = int(tn / h)
x = ee.explicit_euler(f, x0, h, N)
t = np.arange(0, tn, h)
fig = plt.figure()
plt.plot(t, x, label="Explicit Euler")
plt.plot(t, (np.exp(0.5 * t) * np.sin(5 * t)), label="Analytical
solution")
#plt.plot(t, np.exp(0.5 * t), label="Analytical solution")
plt.xlabel('Timesteps t')
plt.ylabel('x(t)=e^(0.5*t) * sin(5*t)')
plt.legend()
plt.grid()
plt.show()
Edit:
As requested here is the current equation I am applying the method to:
y'-y=-0.5*e^(t/2)*sin(5t)+5e^(t/2)*cos(5t)
Where y(0)=0.
I would like to make clear however that this behaviour doesn't occur just for this equation but all equations where the slope has a change in sign, or oscillating behaviour.
Edit 2:
Ok thanks. Yes the code below does indeed work. But I have one further question. In the simple example I had for the exponential function, I had defined a method:
def f(x):
return x
for the system f'(x)=x. This gave the output of my first graph which looks correct. I then defined another function:
def k(x):
return cos(x)
for the system f'(x)=cos(x), this does not give expected output. But when I change the function definition to
def k(t, x):
return cos(t)
I get the expected output. If I change my function
def f(t, x):
return t
I get an incorrect output. Am I always actually evaluating the function at a time step and is it just by chance for the system x'=x that at each time step the value is just the value of x?
I had understood that the Euler method used the value of the previously calculated value in order to get the next value. But if I run code for my function k(x)=cos(x), I get output pictured below, which must be incorrect. This now uses the updated code you provided.
def k(t, x):
return np.cos(x)
h = 0.1 # Step size
x0 = (0, 0) # Initial point of iteration
tn = 10 # Time step to iterate to
N = int(tn / h) # Number of steps
x = ee.explicit_euler(k, x0, h, N)
t = np.arange(0, tn, h)

The problem is that you have incorrectly raised the function g, you want to solve the equation:
From where we observe that:
y' = y -0.5*e^(t/2)*sin(5t)+5e^(t/2)*cos(5t)
Then we define the function f(t, y) = y -0.5*e^(t/2)*sin(5t)+5e^(t/2)*cos(5t) as:
def f(t, y):
return y -0.5 * np.exp(t * 0.5) * np.sin(5 * t) + 5 * np.exp(t * 0.5) * np.cos(5 * t)
The initial point of iteration is f0=(t(0), y(0)):
f0 = (0, 0)
Then from Euler's equations:
def explicit_euler(df, x0, h, N):
"""Solves an ODE IVP using the Explicit Euler method.
Keyword arguments:
df - The derivative of the system you wish to solve.
x0 - The initial value of the system you wish to solve.
h - The step size.
N - The number off steps.
"""
x = np.zeros(N)
t, x[0] = x0
for i in range(0, N-1):
x[i+1] = x[i] + h * df(t ,x[i])
t += h
return x
Complete Code:
def explicit_euler(df, x0, h, N):
"""Solves an ODE IVP using the Explicit Euler method.
Keyword arguments:
df - The derivative of the system you wish to solve.
x0 - The initial value of the system you wish to solve.
h - The step size.
N - The number off steps.
"""
x = np.zeros(N)
t, x[0] = x0
for i in range(0, N-1):
x[i+1] = x[i] + h * df(t ,x[i])
t += h
return x
def df(t, y):
return -0.5 * np.exp(t * 0.5) * np.sin(5 * t) + 5 * np.exp(t * 0.5) * np.cos(5 * t) + y
h = 0.001
f0 = (0, 0)
tn = 4
N = int(tn / h)
x = explicit_euler(df, f0, h, N)
t = np.arange(0, tn, h)
fig = plt.figure()
plt.plot(t, x, label="Explicit Euler")
plt.plot(t, (np.exp(0.5 * t) * np.sin(5 * t)), label="Analytical solution")
#plt.plot(t, np.exp(0.5 * t), label="Analytical solution")
plt.xlabel('Timesteps t')
plt.ylabel('x(t)=e^(0.5*t) * sin(5*t)')
plt.legend()
plt.grid()
plt.show()
Screenshot:
Dump y' and what is on the right side is what you should place in the df function.
We will modify the variables to maintain the same standard for the variables, and will y be the dependent variable, and t the independent variable.
Equation 2: In this case the equation f'(x)=cos(x) will be rewritten to:
y'=cos(t)
Then:
def df(t, y):
return np.cos(t)
In conclusion, if we have an equation of the following form:
y' = f(t, y)
Then:
def df(t, y):
return f(t, y)

Related

Speeding up Sympy solve() on a particular equation

I am trying to solve an equation but the solve() function is taking over 10 minutes even on a high RAM colab notebook. Are there any simplifications to the problem that I can take to speed this along? Here is the code:
x, y, x_0, y_0, x_new, y_new, t, f = symbols('x y x_0 y_0 x_new y_new t f')
D = (2 * (1 - t) * sqrt(x * y) + t * (x + y)) / (2 * (x + y) * sqrt(x * y))
D_old = D.subs([(x, x_0), (y, y_0)])
D_new = D.subs([(x, x_new), (y, y_new)])
delta_D = D_new - D_old
target = Eq(delta_D, f)
answer = solve(target, x_new)
If it is taking a long time you must be trying to solve for one of the x or y values. This will require solving a messy cubic equation in many variables. It would be better if you just substituted in the values of interest and then used nsolve to find the roots of interest. Otherwise, you can get a symbolic solution to the generic cubic g3 = solve(a*x**3 + b*x**2 + c*x + d, x) and then substitute in the corresponding expressions for the coefficients of collect(sympy.solvers.solvers.unrad(target.rewrite(Add))[0], v) where v is the variable of interest. But I won't bog this down with more details until it is clear what you really want to do.

How to solve the differential equation?

I want to solve the deferential equation
dydt = r * (Y ** p) * (1 - (Y / K) ** alpha)
I tried to write the code like :
def func(Y, r, p, K, alpha):
dydt = r * (Y ** p) * (1 - (Y / K) ** alpha)
return dydt
t = np.linspace(0, len(df), len(df))
# I used 1 to initialize my parameters ( is there a better way ?)
r = 1; p = 1; K = 1; alpha = 1
y0 = r,p,K,alpha
ret = odeint(func, y0, t)
but when I try to execute the third block I get
TypeError: func() missing 3 required positional arguments: 'p', 'K', and 'alpha'
However I tried to use ret = odeint(func, y0, t, args=(p,K, alpha))
but this resulted in a three straight lines, when the equation is supposed to return a logistic curve.
how can I try to put r in the argument and why I need to specify the arguments? how can I get the final shape (logistic curve)
Note: to understand the parameters: Y represents the cumulative number of cases at time t, r is the growth rateat the early stage, and K is the final epidemic size.𝑝∈[0,1]is a parameter that allows the model to capture different growth profiles including the constant incidence (𝑝=0), sub-exponential growth (0<𝑝<1)and exponential growth (𝑝=1).
def func(Y, t, r, p, K, alpha):
return r * (Y ** p) * (1 - (Y / K) ** alpha)
You must add the t parameter in the ODEINT method.
y0 = 0.5 # Your initial condition.
params = (1, 1, 1, 1) # r, p, K, alpha
sol = odeint(func, y0, t, args=params)
From the source! Scipy ODEINT

Stop Integrating when Output Reaches 0 in scipy.integrate.odeint

I've written a code which looks at projectile motion of an object with drag. I'm using odeint from scipy to do the forward Euler method. The integration runs until a time limit is reached. I would like to stop integrating either when this limit is reached or when the output for ry = 0 (i.e. the projectile has landed).
def f(y, t):
# takes vector y(t) and time t and returns function y_dot = F(t,y) as a vector
# y(t) = [vx(t), vy(t), rx(t), ry(t)]
# magnitude of velocity calculated
v = np.sqrt(y[0] ** 2 + y[1] **2)
# define new drag constant k
k = cd * rho * v * A / (2 * m)
return [-k * y[0], -k * y[1] - g, y[0], y[1]]
def solve_f(v0, ang, h0, tstep, tmax=1000):
# uses the forward Euler time integration method to solve the ODE using f function
# create vector for time steps based on args
t = np.linspace(0, tmax, tmax / tstep)
# convert angle from degrees to radians
ang = ang * np.pi / 180
return odeint(f, [v0 * np.cos(ang), v0 * np.sin(ang), 0, h0], t)
solution = solve_f(v0, ang, h0, tstep)
I've tried several loops and similar to try to stop integrating when ry = 0. And found this question below but have not been able to implement something similar with odeint. solution[:,3] is the output column for ry. Is there a simple way to do this with odeint?
Does scipy.integrate.ode.set_solout work?
Checkout scipy.integrate.ode here. It is more flexible than odeint and helps with what you want to do.
A simple example using a vertical shot, integrated until it touches ground:
from scipy.integrate import ode, odeint
import scipy.constants as SPC
def f(t, y):
return [y[1], -SPC.g]
v0 = 10
y0 = 0
r = ode(f)
r.set_initial_value([y0, v0], 0)
dt = 0.1
while r.successful() and r.y[0] >= 0:
print('time: {:.3f}, y: {:.3f}, vy: {:.3f}'.format(r.t + dt, *r.integrate(r.t + dt)))
Each time you call r.integrate, r will store current time and y value. You can pass them to a list if you want to store them.
Let's solve this as the boundary value problem that it is. We have the conditions x(0)=0, y(0)=h0, vx(0)=0, vy(0)=0 and y(T)=0. To have a fixed integration interval, set t=T*s, which means that dx/ds=T*dx/dt=T*vx etc.
def fall_ode(t,u,p):
vx, vy, rx, ry = u
T = p[0]
# magnitude of velocity calculated
v = np.hypot(vx, vy)
# define new drag constant k
k = cd * rho * v * A / (2 * m)
return np.array([-k * vx, -k * vy - g, vx, vy])*T
def solve_fall(v0, ang, h0):
# convert angle from degrees to radians
ang = ang * np.pi / 180
vx0, vy0 = v0*np.cos(ang), v0*np.sin(ang)
def fall_bc(y0, y1, p): return [ y0[0]-vx0, y0[1]-vy0, y0[2], y0[3]-h0, y1[3] ]
t_init = [0,1]
u_init = [[0,0],[0,0],[0,0], [h0,0]]
p_init = [1]
res = solve_bvp(fall_ode, fall_bc, t_init, u_init, p_init)
print res.message
if res.success:
print "time to ground: ", res.p[0]
# res.sol is a dense output, evaluation interpolates the computed values
return res.sol
sol = solve_fall(300, 30, 20)
s = np.linspace(0,1,501)
u = sol(s)
vx, vy, rx, ry = u
plt.plot(rx, ry)

Euler method approximation is too accurate

I'm trying to code Euler's approximation method to solve the harmonic oscillator problem, and then compare it on a plot with the exact solution. However, I'm finding that my approximation seems to be too good (even for larger step sizes), especially since I know the error is supposed to increase as time goes on. Am I doing something wrong in my Euler's method code? It's all written below.
import numpy as np
import matplotlib.pyplot as plt
w = 1.0 #frequency of oscillation
x_0 = 1.0 #initial position
h = 0.6 #step size
t_0 = 0 #starting time
n = 20
t = np.arange(t_0, n, h) #t = t_0 + nh (h has units of seconds)
y = np.array([[0.0, 0.0]]*len(t))
def x(t, x_0, w): #exact solution
return x_0*np.cos(w*t)
def x_prime(t, x_0, w): #first derivative of solution (which is also v)
return -x_0*w*np.sin(w*t)
y[0] = [x_0, 0.0] #starting velocity is 0
for i in range(1, len(t)):
# Euler's method
y[i] = y[i-1] + np.array([x_prime(t[i-1], x_0, w), -w**2 * x(t[i-1], x_0, w)]) * h
xlist = [item[0] for item in y] #list of x values at each t value
vlist = [item[1] for item in y] #list of velocity values at each t value
plt.plot(t, xlist, label='Euler approximation')
plt.plot(t, x(t, x_0, w), label='Exact solution')
plt.xlabel('t')
plt.ylabel('x(t)')
plt.legend(loc='upper right')
And my plot for this code outputs as:
Your problem is that you compute the slopes for the Euler method from the exact solution. You should use the previous approximation instead,
# Euler's method
y[i] = y[i-1] + np.array([y[i-1,1], -w**2 * y[i-1,0]]) * h
or use a function
def f(t,y): x, dotx = y; return np.array([ dotx, -w**2*x])
...
for i in range(1, len(t)):
# Euler's method
y[i] = y[i-1] + f(t[i-1],y[i-1]) * h
Then you will get the expected rapidly diverging behavior, here for h=0.1:
Btw., it might be simpler to write
xlist, vlist = y.T

RK4-method and Euler method working only for certain formulae

I tried to write an algorithm for solving the non-linear ODE
dr/dt = r(t)+r²(t)
which has (one possible) solution
r(t) = r²(t)/2+r³(t)/3
For that I implemented both the euler method and the RK4 method in python. For error checking I used the example on rosettacode:
dT/dt = -k(T(t)-T0)
with the solution
T0 + (Ts − T0)*exp(−kt)
Thus, my code now looks like
import numpy as np
from matplotlib import pyplot as plt
def test_func_1(t, x):
return x*x
def test_func_1_sol(t, x):
return x*x*x/3.0
def test_func_2_sol(TR, T0, k, t):
return TR + (T0-TR)*np.exp(-0.07*t)
def rk4(func, dh, x0, t0):
k1 = dh*func(t0, x0)
k2 = dh*func(t0+dh*0.5, x0+0.5*k1)
k3 = dh*func(t0+dh*0.5, x0+0.5*k2)
k4 = dh*func(t0+dh, x0+k3)
return x0+k1/6.0+k2/3.0+k3/3.0+k4/6.0
def euler(func, x0, t0, dh):
return x0 + dh*func(t0, x0)
def rho_test(t0, rho0):
return rho0 + rho0*rho0
def rho_sol(t0, rho0):
return rho0*rho0*rho0/3.0+rho0*rho0/2.0
def euler2(f,y0,a,b,h):
t,y = a,y0
while t <= b:
#print "%6.3f %6.5f" % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
x0 = 100
x_vec_rk = []
x_vec_euler = []
x_vec_rk.append(x0)
h = 1e-3
for i in range(100000):
x0 = rk4(newtoncooling, h, x0, i*h)
x_vec_rk.append(x0)
x0 = 100
x_vec_euler.append(x0)
x_vec_sol = []
x_vec_sol.append(x0)
for i in range(100000):
x0 = euler(newtoncooling, x0, 0, h)
#print(i, x0)
x_vec_euler.append(x0)
x_vec_sol.append(test_func_2_sol(20, 100, 0, i*h))
euler2(newtoncooling, 0, 0, 1, 1e-4)
x_vec = np.linspace(0, 1, len(x_vec_euler))
plt.plot(x_vec, x_vec_euler, x_vec, x_vec_sol, x_vec, x_vec_rk)
plt.show()
#rho-function
x0 = 1
x_vec_rk = []
x_vec_euler = []
x_vec_rk.append(x0)
h = 1e-3
num_steps = 650
for i in range(num_steps):
x0 = rk4(rho_test, h, x0, i*h)
print "%6.3f %6.5f" % (i*h, x0)
x_vec_rk.append(x0)
x0 = 1
x_vec_euler.append(x0)
x_vec_sol = []
x_vec_sol.append(x0)
for i in range(num_steps):
x0 = euler(rho_test, x0, 0, h)
print "%6.3f %6.5f" % (i*h, x0)
x_vec_euler.append(x0)
x_vec_sol.append(rho_sol(i*h, i*h+x0))
x_vec = np.linspace(0, num_steps*h, len(x_vec_euler))
plt.plot(x_vec, x_vec_euler, x_vec, x_vec_sol, x_vec, x_vec_rk)
plt.show()
It works fine for the example from rosettacode, but it is unstable and explodes (for t > 0.65, both for RK4 and euler) for my formula. Is therefore my implementation incorrect, or is there another error I do not see?
Searching for the exact solution of your equation:
dr/dt = r(t)+r²(t)
I've found:
r(t) = exp(C+t)/(1-exp(C+t))
Where C is an arbitrary constant which depends on initial conditions. It can be seen that for t -> -C the r(t) -> infinity.
I do not know what initial condition you use, but may be you meet with this singularity when calculate numerical solution.
UPDATE:
Since your initial condition is r(0)=1 the constant C is C = ln(1/2) ~ -0.693. It can explain why your numerical solution crashes at some t>0.65
UPDATE:
To verify your code you can simply compare your numerical solution calculated for, say 0<=t<0.6 with exact solution.

Categories