This document provides a self-contained, code-first introduction to the core ideas of the Finite Element Method (FEM) using only NumPy. No external FEM library is required – the goal is to make every step explicit and easy to follow.
def assemble_stiffness(nodes, elements): n =len(nodes) K = np.zeros((n, n))for el in elements: i, j = el h = nodes[j] - nodes[i]# k^e_{ab} = ∫ φ'_a φ'_b dx over the element (weak-form Galerkin) ke = np.array([[1, -1], [-1, 1]]) / h K[np.ix_([i, j], [i, j])] += kereturn KK = assemble_stiffness(nodes, elements)print("Global stiffness matrix K:\n", np.round(K, 3))
For linear elements on a uniform mesh the FEM solution is exact at the nodes (super-convergence), so the error is effectively zero up to floating-point rounding.
5 · Visualise
import matplotlib.pyplot as pltx_fine = np.linspace(0, 1, 200)u_fine = x_fine +0.5* (x_fine - x_fine**2)fig, ax = plt.subplots(figsize=(6, 3.5))ax.plot(x_fine, u_fine, "k-", lw=1.5, label="Analytical")ax.plot(nodes, u, "ro--", lw=1, label="FEM nodes")ax.set_xlabel("x")ax.set_ylabel("u(x)")ax.set_title("1-D Poisson – FEM vs Analytical")ax.legend()plt.tight_layout()plt.show()