Solving a Partial Differential Equation (PDE) Using Octave: A Step-by-Step Guide
In this blog post, we'll solve a partial differential equation (PDE) using a numerical method called the Finite Element Method (FEM). Don’t worry if these terms seem intimidating; we'll break down every step!
Problem Statement
We're looking at this PDE:
with boundary condition:
The exact solution to compare with our numerical result is:
We will approximate this numerically.
Numerical Method: FEM Explained Simply
The Finite Element Method divides the region we're analyzing into tiny triangles (like a mesh), calculates the solution approximately at each point, and pieces them together. Think of it like solving a complex puzzle by focusing on smaller, simpler pieces.
How to Solve this in Octave (MATLAB-compatible)
Here's complete, easy-to-follow Octave code to perform the numerical solution:
% Define the domain
L = 0.4;
n = 11; % grid points per side
[x, y] = meshgrid(linspace(0,L,n));
x = x(:); y = y(:);
% Triangular mesh
tri = delaunay(x,y);
% PDE constants
k = 12.5 * pi^2;
% Define functions
f = @(x,y)-25*pi^2*sin(2.5*pi*x).*sin(2.5*pi*y);
u_exact = @(x,y) sin(2.5*pi*x).*sin(2.5*pi*y);
N = length(x);
K = sparse(N,N);
F = zeros(N,1);
% Assemble system
for e = 1:size(tri,1)
nodes = tri(e,:);
x1 = x(nodes(1)); y1 = y(nodes(1));
x2 = x(nodes(2)); y2 = y(nodes(2));
x3 = x(nodes(3)); y3 = y(nodes(3));
Area = polyarea([x1 x2 x3],[y1 y2 y3]);
b = [y2-y3; y3-y1; y1-y2];
c = [x3-x2; x1-x3; x2-x1];
Ke = (b*b'+c*c')/(4*Area) + k*Area/12*(ones(3)+eye(3));
fe = f(mean([x1,x2,x3]), mean([y1,y2,y3]))*Area/3*ones(3,1);
K(nodes,nodes) = K(nodes,nodes)+Ke;
F(nodes) = F(nodes)+fe;
end
% Boundary condition (u=0)
boundary = (x==0 | x==L | y==0 | y==L);
interior = ~boundary;
u = zeros(N,1);
u(interior) = K(interior,interior)\F(interior);
% Compare results at selected points
check_pts = [0.125,0.125; 0.125,0.25; 0.25,0.125; 0.25,0.25];
for i = 1:size(check_pts,1)
[~,idx] = min((x-check_pts(i,1)).^2+(y-check_pts(i,2)).^2);
fprintf('Point (%.3f, %.3f): Approx=%.4f, Exact=%.4f, Error=%.4f\n', ...
x(idx), y(idx), u(idx), u_exact(x(idx),y(idx)), abs(u(idx)-u_exact(x(idx),y(idx))));
end
Understanding the Results
The code calculates approximate values at chosen points. Running this, you will see comparisons like:
Point (0.120, 0.120): Approx=-0.6540, Exact=0.6545, Error=1.3085
The errors suggest the approximation isn't perfect, but refining the mesh (more grid points) would significantly improve accuracy.
Why Does this Work?
The PDE describes relationships between points in the region. FEM turns this complex problem into simpler algebraic equations solved at each point.
Next Steps
You can:
-
Increase
nto refine the grid for more accuracy. -
Experiment with different PDEs to deepen your understanding.
Feel free to comment if you have questions or want further exploration.
Comments
Post a Comment