Solving Poisson's Equation Using 5-Point Stencil In A Rectangular Domain

Solving Poisson's Equation Using 5-Point Stencil:

Example:Consider the Poisson's equation on a unit square domain with the source term given by $q(x)=100*\sin(\pi x)*\sin(\pi y)$. The boundaries of the domain are maintained at $u=0$. Reactangular region: $0 \leq x,y \leq 1$. Determine the solution using finite difference method.


Solution:5-point stencil and Gauss-Seidel methods are used to solve Poisso's equations. Here a Mathematica code is give to sove this following program. dx = 0.1;
x = Range[0, 1, dx];
y = x;
n = Length[x];m = Length[y];
xy = Transpose[Join[{x}, {y}]];
(*Print["xy: ",xy//MatrixForm];*)
xMeshgrid = ConstantArray[10, {n, n}];
yMeshgrid = ConstantArray[10, {m, m}];
o[Do[xMeshgrid[[i, j]] = x[[i]];
yMeshgrid[[j, i]] = y[[i]], {j, 1, m}], {i, 1, n}];
(*Print["xMeshgrid: ",xMeshgrid//MatrixForm];
Print["yMeshgrid: ",yMeshgrid//MatrixForm];*)
X = Transpose[xMeshgrid];
Y = Transpose[yMeshgrid];
(*Print["X: ",X//MatrixForm];
Print["Y: ",Y//MatrixForm];*)
XY = Transpose[Join[{Flatten[xMeshgrid]}, {Flatten[yMeshgrid]}]];
(*Print["meshgrid XY: ",XY//MatrixForm];*)
h = 1/(n - 1); k = 1/(m - 1);
q = 100*Sin[Pi X]*Sin[Pi Y];
q[[-1, ;;]] = 0;
q[[;; , -1]] = 0;
Print["q : ", q // MatrixForm];
u = ConstantArray[0, {n, n}];
u0 = u;
res = 1;
tol = 10^-6;
iter = 0;

While[res > tol, iter = iter + 1;(*Print["Iteration: ",iter];*)
  Do[Do[u[[i, j]] = ((u[[i + 1, j]] + u[[i - 1, j]])/h^2 + (u[[i, j + 1]] + u[[i, j - 1]])/k^2 + q[[i, j]])/(2/h^2 + 2/k^2),
    {j, 2, n - 1}],
   {i, 2, n - 1}]; res = Max[Abs[u0 - u]];
(*Print["res: ",res];*)
u0 = u];
Print["Total iteration requird for [", n, "x", n, "] grid is: ", iter];
Print["solution u: ", u0 // MatrixForm]
data = MapThread[Append, {XY, Flatten[u0]}]
p1 = ListContourPlot[data, ContourLabels -> All, FrameLabel -> {"x", "y"}, PlotLegends -> Automatic]


Here contour plot of this solution is attached below:

  • By changing the value of dx, you can change the grid size. Warning! If you increase grid size from 21by21 to 81by81 or more it will take very large number of iterations to converge the solution. Here Gauss-Seidel method is applied.
  • Mathematica Official website: Visit Mathematica
  • Mathematica Documentation Center: Visit Mathematica Documentation Center

Comments

Popular posts from this blog

Solve Poisson's Equation in Matlab

Backward Substitution in MATLAB

Solve Poissons Equation using 5-Point Stencil with SOR method