From-scratch implementations of the Finite Element Method (FEM) in Python and C, applied to two physical problems. Each solution derives the weak form using the Rayleigh-Ritz method, assembles the global stiffness matrix element by element, and solves the resulting linear system with a custom numerical solver.
Solve the 2D Poisson equation on a square domain with homogeneous Dirichlet boundary conditions:
The diagonal symmetry of the domain reduces the problem to a triangular region discretized with 15 nodes and 15 linear triangular elements.
The weak form is derived by multiplying by a test function φ and applying the divergence theorem:
Linear shape functions N₁, N₂, N₃ are used over each triangular element to build the master stiffness matrix, which is then assembled into the global system KU = f and solved with Gaussian elimination with partial pivoting.
pip install numpy matplotlib
python poisson-equation/poisson_fem.pyFind the initial velocity of a damped spring-mass system such that the first full oscillation cycle lasts 6.4 s:
The weak form is obtained by multiplying by a test function w and integrating by parts over each time element:
Linear shape functions N₁(ξ) = (1-ξ)/2 and N₂(ξ) = (1+ξ)/2 yield the master element. The global system is assembled by overlapping consecutive element matrices and solved with a custom Gauss-Jordan elimination implementation in C.
FEM nodal values match the analytical solution x(t) = e^{−0.4t} cos(0.9165t) with high precision:
| Node | t (s) | FEM x (cm) | Analytical x (cm) |
|---|---|---|---|
| 1 | 0 | 1.0000 | 1.0000 |
| 2 | 3.2 | −0.2421 | −0.2421 |
| 3 | 6.4 | 0.0838 | 0.0836 |
gcc spring-mass-damper/spring_mass_damper.c -o spring_mass_damper
./spring_mass_damperPython · NumPy · Matplotlib · C
