Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Numerically solving ODE’s
Lecture 5
Differential Equations • Ordinary Differential Equations (ODE)
– Function(s) of one independent variable (e.g. f(x), g(t)) • Partial Differential Equations
– Function(s) of two or more independent variables: f(x,y)
• Can have coupled sets of ODE – E.g. f(x), g(x) depend on each other
• ODE’s (relatively) easy to solve – PDE’s can be harder
The Pendulum
θ l
mg
F=ma in direction of θ:
If θ is small, then sinθ ~ θ
Solution: θ=θ0 cos((g/l)1/2 t)
Initial conditions θ=θ0 at t=0
€
d2θdt 2
+glsinθ = 0
€
d2θdt 2
+glθ = 0
The linear Pendulum
Solution: θ=θ0 cos((g/l)1/2 t)
Initial conditions θ=θ0 at t=0
€
d2θdt 2
+glθ = 0
The (non-linear) Pendulum
For large θ, the ODE is non-linear:
How do we solve this?
€
d2θdt 2
+glsinθ = 0
Euler’s method Take a general first-order ODE:
0 t1 t2 t3
x0 x1
x2
x3
Approximate x(t1=h) as:
Approximate x(t2=2h) as:
and so on…
In general:
€
dxdt
= f (x, t)
€
x1 = x0 + hf (x0,0)
€
x2 = x1 + hf (x1,h)
€
xn+1 = xn + hf (xn,tn )
Apply Euler to Pendulum 2nd order ODE:
First, re-write in dimensionless form:
Define new time variable:
To get:
€
d2θdt 2
+glsinθ = 0
€
τ = t(l /g)−1/ 2
€
d2θdτ 2
+ sinθ = 0
Apply Euler to Pendulum 2nd order ODE:
Split into two coupled 1st order ODE’s:
Apply Euler’s method to both equations
€
d2θdτ 2
+ sinθ = 0
€
dθdτ
= y
€
dydτ
= −sin(θ)
from math import *
def euler(dt, y, theta): dtheta = dt * y dy = dt * (-sin(theta)) y = y + dy theta = theta + dtheta return (y,theta)
theta = 0.5 y = 0 t = 0 tstop = 40.0 dt = 0.05
while (t < tstop): (y,theta) = euler(dt, y, theta) t = t + dt print t, theta, y
Python program to solve Pendulum using Euler’s method
Set initial conditions
Use euler function to go from n to n+1
Function that does one Euler step
Apply Euler to Pendulum 800 steps
Apply Euler to Pendulum 800 steps
4000 steps
Phase space diagram
θ
dθ/dt Pendulum at one moment in time
Phase space diagram 800 steps
Phase space diagram 800 steps
4000 steps
Improved Euler’s method
0 t1 t2 t3
x1 x2
x3
Instead of using slope just at xn:
Use an average slope:
But xn+1 appears on RHS?!
Solution: use Euler method to get an approximate xn+1
€
xn+1 = xn +12h( f (xn,tn ) + f (xn+1,tn+1))
€
xn+1 = xn + hf (xn,tn )
Improved Euler’s method
c = hf(x,t)
xnew = x + c
c = hf(x,t) d = hf(x+c, t+h) xnew = x + (c+d)/2
Original Euler method
Improved Euler method
Apply Improved Euler to Pendulum 800 steps
Euler
4000 steps Euler (red)
800 steps Improved Euler (blue)
Improved Euler: Phase space diagram 800 steps
Euler
4000 steps Euler (red)
800 steps Improved Euler
High amplitude pendulum
High amplitude pendulum
High amplitude pendulum
High amplitude pendulum
High amplitude pendulum
Summary • Euler method
– slope at xn Error ~ h
• Improved Euler – slope averaged over 2 points – Error ~ h2
• Runge-Kutta – Slope averaged over 4 points – Error ~ h4
• Phase diagram (velocity vs. position)