Copyright (C) 2020 Andreas Kloeckner
import sympy as s
s.init_printing()
Establish some variables that we'll need:
u = s.Function("u")
a, x, t, h_x, h_t = s.symbols("a, x, t, h_x, h_t")
xi, xi_1, xi_2, tau = s.symbols("xi, xi1, xi2, tau")
taylor
is a utility function that spits out a taylor expansion for $f(x+h)$, optionally including a remainder term, with all variables under our control.
def taylor(f, x, h, n, remainder_variable=None):
result = sum(f.diff(x, i)*h**i/s.factorial(i) for i in range(n))
if remainder_variable:
result += f.diff(x, n).subs(x, remainder_variable)*h**n/s.factorial(n)
return result
taylor(u(x,t), x, h_x, 3, xi)
Assign the PDE we're solving to pde
:
pde = u(x, t).diff(t) + a * u(x, t).diff(x)
pde
Write out the scheme we're analyzing, in this case ETCS:
etcs = (
(u(x, t+h_t) - u(x, t))/h_t
+
a*(u(x+h_x, t) - u(x-h_x, t))/(2*h_x))
etcs
Follow this general pattern:
etcs
.subs(u(x, t+h_t), taylor(u(x,t), t, h_t, 2, tau))
to arrive at the truncation error.
⚠️ Make sure to keep the two $x$ remainder terms separate.
etcs_taylor = (
etcs
.subs(u(x, t+h_t), taylor(u(x,t), t, h_t, 2, tau))
.subs(u(x+h_x, t), taylor(u(x,t), x, h_x, 3, xi_1))
.subs(u(x-h_x, t), taylor(u(x,t), x, -h_x, 3, xi_2))
)
s.simplify(etcs_taylor - pde)