I am trying to solve the following problem via a finite difference approximation:
$u_t = k \, u_{xx}$, on $0 < x < L$ and $t > 0$;
$u(0,t) = u(L,t) = 0$;
$u(x,0) = f(x)$.
I take $u(x,0) = f(x) = x^2$ for my problem.
Programming is not my forte at all, so I am having some issues with the implementation. Here is my code:
## This program is to implement a Finite Difference method approximation
## to solve the Heat Equation, u_t = k * u_xx,
## in 1D w/out sources & on a finite interval 0 < x < L. The PDE
## is subject to B.C: u(0,t) = u(L,t) = 0,
## and the I.C: u(x,0) = f(x).
import numpy as np
import matplotlib.pyplot as plt
# definition of solution to u_t = k * u_xx
def u(x,t):
return u
# definition of initial condition function
def f(x):
return x^2
# parameters
L = 1
T = 10
N = 10
M = 10
s = 0.25
# uniform mesh
x_init = 0
x_end = L
dx = float(x_end - x_init) / N
# time discretization
t_init = 0
t_end = T
dt = float(t_end - t_init) / M
t = np.zeros(M+1)
t = np.arange(t_init, t_end, dt)
# Boundary Conditions
for m in xrange(0, M):
t[m] = m * dt
u(0, t[m]) = 0
u(N, t[m]) = 0
# Initial Conditions
for j in xrange(0, N):
x[j] = j * dx
u(x[j], 0) = f(x[j])
# finite difference scheme
for j in xrange(1, N-1):
u(x[j],t[m+1]) = u(x[j],t[m]) + s * ( u(x[j+1],t[m]) -
2 * u(x[j],t[m]) + u(x[j-1],t[m]) )
So in particular, I am wondering (1) if my function definitions are okay? (2) is my uniform mesh and time discretization okay? (3) am I selecting reasonable values for the parameters? (I know that the approximation is more accurate for smaller $\Delta x$ and $\Delta t$, with the disadvantage of increased computing time..)
(4) how are my loops (for the initial/boundary conditions)? I get the feeling I need a nested loop for the finite difference scheme.. One for loop for the values of j and another for loop going through each value m in time. Is this correct? ... Also, I keep getting the error: u(0, t[m]) = 0 "can't assign to function call." What is wrong there?
Thanks in advance for the help! As I mentioned, my programming skills are not very strong so I feel like a fish out of water doing this.
def u(x, t): return u
, while it happens to be valid python, is not at all meaningful here. Perhaps it might be easier to start with a beginner programming textbook of some sort? $\endgroup$