Skip to content
LumenaryAcademy
Solids 75 min

The finite element method

How engineers compute stresses and deflections in parts of any shape — elements, stiffness matrices, assembly and boundary conditions, a working truss solver, and the discipline of convergence and verification.

Code tested · 6AI-draftedAwaiting review by a mechanical engineer

Your guides: Chloe · The Designer, Margaret · The Test Engineer, Gideon · The Checker

MotivationH

From formulas to any shape

Every formula in this level so far, δ=NL/(EA)\delta = NL/(EA), τ=Tr/J\tau = Tr/J, σ=−My/I\sigma = -My/I, Euler's load, works for long, slender, simple parts. Now look at a real one: a cast aluminium suspension upright, a crankshaft, a titanium hip implant, the frame of a phone, a turbine disc with its cooling holes and fir-tree slots. None of them is a bar, a shaft or a beam. Their stresses can be measured on a prototype, but a designer needs them before anything is made, for dozens of variants.

The finite element method (FEM) answers that need. It chops the part into many small, simple pieces, the elements, writes down how each piece deforms and carries load, and assembles them into a large system of linear equations that a computer solves. The same method computes temperatures, vibrations, buckling loads, electromagnetic fields and flows, and in 2026 almost every load-bearing product, from bicycles to bridges and aircraft, is analysed with it before it is built.

You already know most of what is inside it. The spring stiffness of a bar from Axial load, torsion and bending, the truss of Trusses and frames, the indeterminate beam of Deflection and buckling: this lesson ties them into one method, builds working solvers in NumPy, and then spends as long on how to check the answers as on how to get them.

IntuitionH

Springs all the way down

The truss solver of the trusses lesson took the forces in the members as unknowns and wrote equilibrium at every joint. That works only when the structure is statically determinate; with one member or support too many, the equilibrium matrix had more columns than rows and the solver refused.

The finite element method takes the displacements of the joints, called nodes, as unknowns instead. Every element is a spring: given how its ends move, it knows how much it stretches, and so what forces it exerts on them. Equilibrium at each node then says that the spring forces balance the applied loads. There is always exactly one equation per unknown displacement, however many members meet at a node, so determinate and indeterminate structures are solved alike. Compatibility, which had to be added by hand in the deflection lesson, is built in, because neighbouring elements share the displacement of the node between them.

1234Fk₁k₂k₃Kassembled stiffness matrix
A tapered bar, fixed at the left and pulled at the right, divided into three elements between four nodes. Each element acts as a spring of stiffness k = EA/L. Each spring adds a 2 × 2 block to the global stiffness matrix K, and blocks overlap where elements share a node, giving a banded matrix.
DefinitionsH

Elements, stiffness and assembly

Definition— element, node and degree of freedom

A mesh divides a structure into elements joined at nodes. The unknowns are the displacements (and, for beams and shells, rotations) of the nodes, the degrees of freedom. Inside each element, the displacement is interpolated from its nodal values by simple shape functions: for a two-node bar, linearly, u(x)=(1−ξ) u1+ξ u2u(x) = (1 - \xi)\,u_1 + \xi\,u_2 with ξ=x/Le\xi = x/L_e.

Definition— element stiffness matrix

The element stiffness matrix ke\mathbf{k}_e maps an element's nodal displacements to the forces it exerts on its nodes. A bar element of length LeL_e, area AA and modulus EE has strain (u2−u1)/Le(u_2 - u_1)/L_e and axial force N=EA(u2−u1)/LeN = EA(u_2 - u_1)/L_e, so

ke=EALe(1−1−11).\mathbf{k}_e = \frac{EA}{L_e}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}.

Definition— assembly, boundary conditions and solution

The global stiffness matrix K\mathbf{K} is the sum of all element matrices, each added into the rows and columns of its own degrees of freedom (assembly). Equilibrium of every node is the linear system Ku=f\mathbf{K}\mathbf{u} = \mathbf{f}, where f\mathbf{f} holds the applied nodal loads. Boundary conditions fix the displacements at supports: the corresponding equations are removed (their unknowns are known), the rest are solved, and the reactions are recovered afterwards as Ku−f\mathbf{K}\mathbf{u} - \mathbf{f} at the supported degrees of freedom. Finally, strains and stresses are computed element by element from the displacements.

Theorem— Properties of the stiffness matrix

K\mathbf{K} is symmetric and positive semidefinite, and uTKu=0\mathbf{u}^\mathsf{T}\mathbf{K}\mathbf{u} = 0 exactly for the rigid-body motions of the structure. Once the supports prevent every rigid-body motion, the reduced matrix is positive definite, so Ku=f\mathbf{K}\mathbf{u} = \mathbf{f} has exactly one solution, and that solution minimises the total potential energy Π=12uTKu−fTu\Pi = \tfrac12\mathbf{u}^\mathsf{T}\mathbf{K}\mathbf{u} - \mathbf{f}^\mathsf{T}\mathbf{u}.

Proof

Each element matrix is ke=(EA/Le) ttT\mathbf{k}_e = (EA/L_e)\,\mathbf{t}\mathbf{t}^\mathsf{T} with t=(−1,1)\mathbf{t} = (-1, 1) for a bar (and similar outer products, or sums of them, for other elements), which is symmetric; sums of symmetric matrices are symmetric. The quadratic form 12uTKu=∑e12(EA/Le) (stretche)2\tfrac12\mathbf{u}^\mathsf{T}\mathbf{K}\mathbf{u} = \sum_e \tfrac12 (EA/L_e)\,(\text{stretch}_e)^2 is the strain energy stored in the structure, a sum of squares, so it is never negative, and it is zero exactly when no element is stretched, that is, for a rigid-body motion. If the supports exclude those, the energy is positive for every allowed u≠0\mathbf{u} \ne \mathbf{0}, which is positive definiteness, and a positive definite matrix is invertible. Finally, the gradient of Π\Pi is Ku−f\mathbf{K}\mathbf{u} - \mathbf{f}, so its stationary point is the solution, and positive definiteness makes it a minimum.

∎

The minimum-energy view is how the method generalises. For any elastic body, the true displacement field minimises the potential energy over all fields that satisfy the supports. The finite element method minimises it over the much smaller family of fields that are piecewise polynomials on the mesh. As the mesh is refined, that family can approximate the true field ever more closely, which is why the answers converge, and why, for these elements, a coarse mesh is too stiff: restricting the shapes a structure may take can only raise the energy minimum.

ComputationC

A 1-D solver: the tapered bar

Start with a steel bar 1 m long whose area tapers linearly from 400 mm² at its fixed end to 100 mm² at its free end, where it is pulled with 20 kN. The exact tip displacement is δ=FLln⁡(A0/A1)/(E(A0−A1))\delta = FL\ln(A_0/A_1)/(E(A_0 - A_1)), and the exact stress at the tip is F/A1=200F/A_1 = 200 MPa. The program assembles bar elements, each using the area at its middle, applies the support by deleting the first row and column, solves, and recovers stresses from the element strains.

python
import numpy as np

# A tapered steel bar, fixed at x = 0, pulled by F at x = L. Area falls linearly from A0 to A1.
E, L, F = 210e3, 1000.0, 20e3                      # MPa (N/mm^2), mm, N
A0, A1 = 400.0, 100.0                              # mm^2
area = lambda x: A0 + (A1 - A0) * x / L

def solve_bar(n):
    """n two-node bar elements; returns node positions, displacements and element stresses."""
    x = np.linspace(0.0, L, n + 1)
    K = np.zeros((n + 1, n + 1))
    for e in range(n):
        Le = x[e + 1] - x[e]
        k = E * area((x[e] + x[e + 1]) / 2) / Le   # element stiffness EA/L (mid-element area)
        K[e:e + 2, e:e + 2] += k * np.array([[1.0, -1.0], [-1.0, 1.0]])   # assemble
    f = np.zeros(n + 1)
    f[-1] = F                                      # the load at the last node
    u = np.zeros(n + 1)
    u[1:] = np.linalg.solve(K[1:, 1:], f[1:])      # boundary condition u0 = 0: drop row and column 0
    stress = E * np.diff(u) / np.diff(x)           # strain = (u2 - u1) / Le in each element
    return x, u, stress, K

x, u, s, K = solve_bar(3)
print("global stiffness matrix for 3 elements (kN/mm):")
print(np.round(K / 1e3, 1))
print("singular before supports? rank", np.linalg.matrix_rank(K), "of", K.shape[0])

exact_tip = F * L * np.log(A0 / A1) / (E * (A0 - A1))
print(f"\nexact tip displacement {exact_tip:.5f} mm, exact stress at the tip {F / A1:.1f} MPa")
print(" elements   tip displacement   error      stress in last element   error")
for n in [1, 2, 4, 8, 16, 32]:
    x, u, s, K = solve_bar(n)
    print(f" {n:6d}     {u[-1]:.5f} mm     {(u[-1] - exact_tip) / exact_tip:+.1e}"
          f"        {s[-1]:6.1f} MPa         {(s[-1] - F / A1) / (F / A1):+.1e}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Three things are worth reading in the output. The assembled matrix for three elements is banded: each node couples only to its neighbours, which is what lets real solvers handle millions of unknowns. Before the support is applied, the matrix has rank 3 out of 4, because the unsupported bar can slide as a rigid body; the theorem said so. And the two columns of errors converge at different rates. The tip displacement error falls by four each time the mesh is halved, from 13% with one element to 0.025% with 32. The stress in the last element, however, approaches 200 MPa only slowly, from 80 MPa to 191 MPa: each element reports a single average stress, so a coarse mesh smears out a peak.

ComputationC

A 2-D truss solver, checked against the bridge

A truss member in the plane joins node aa to node bb at an angle θ\theta to the xx axis. Each node now has two displacements, (u,v)(u, v). With c=cos⁡θc = \cos\theta and s=sin⁡θs = \sin\theta, the member's stretch is the difference of its end displacements projected on its own axis,

δ=c (ub−ua)+s (vb−va)=tTd,t=(−c,−s,c,s),d=(ua,va,ub,vb),\delta = c\,(u_b - u_a) + s\,(v_b - v_a) = \mathbf{t}^\mathsf{T}\mathbf{d}, \qquad \mathbf{t} = (-c, -s, c, s), \quad \mathbf{d} = (u_a, v_a, u_b, v_b),

so its axial force is N=(EA/L) δN = (EA/L)\,\delta, and its stiffness matrix in global coordinates is

ke=EAL t tT.\mathbf{k}_e = \frac{EA}{L}\,\mathbf{t}\,\mathbf{t}^\mathsf{T}.

abuₐvₐu_bv_bθmember axisstretch δ = c (u_b − uₐ) + s (v_b − vₐ)
A plane truss element from node a to node b at angle θ. Each node has two displacements, u along x and v along y. Only the component of their difference along the member stretches it.

The block builds the solver and runs it on the Pratt truss bridge of the trusses lesson: six 4 m panels, 4 m deep, 50 kN at each deck joint, a pin at L0L_0 and a roller at L6L_6. Every member is given a steel area of 3000 mm². It then rebuilds that lesson's equilibrium matrix to compare the member forces, and finally pins both ends, which the equilibrium method could not handle.

python
import numpy as np

def truss_fem(nodes, members, fixed, loads, E, A):
    """Plane truss by the stiffness method. fixed: list of (node, 0 for x or 1 for y).
    Returns displacements (n x 2), member axial forces (tension +) and reactions (n x 2)."""
    P = np.asarray(nodes, dtype=float)
    ndof = 2 * len(P)
    K = np.zeros((ndof, ndof))
    for (a, b), Ae in zip(members, A):
        d = P[b] - P[a]
        Le = np.linalg.norm(d)
        c, s = d / Le
        t = np.array([-c, -s, c, s])               # stretch of the member = t . (u_a, v_a, u_b, v_b)
        dofs = [2*a, 2*a + 1, 2*b, 2*b + 1]
        K[np.ix_(dofs, dofs)] += E * Ae / Le * np.outer(t, t)    # element stiffness, assembled
    f = np.zeros(ndof)
    for node, (fx, fy) in loads.items():
        f[2*node:2*node + 2] = fx, fy
    known = [2*n + k for n, k in fixed]            # restrained degrees of freedom (u = 0)
    free = [i for i in range(ndof) if i not in known]
    u = np.zeros(ndof)
    u[free] = np.linalg.solve(K[np.ix_(free, free)], f[free])
    R = K @ u - f                                  # reactions appear only at restrained dofs
    N = []
    for (a, b), Ae in zip(members, A):
        d = P[b] - P[a]
        Le = np.linalg.norm(d)
        c, s = d / Le
        N.append(E * Ae / Le * (c * (u[2*b] - u[2*a]) + s * (u[2*b + 1] - u[2*a + 1])))
    return u.reshape(-1, 2), np.array(N), R.reshape(-1, 2), K

# The Pratt truss of the trusses lesson: 6 panels of 4 m, 4 m deep, 50 kN at L1..L5
names = [f"L{i}" for i in range(7)] + [f"U{i}" for i in range(1, 6)]
nodes = [(4.0 * i, 0.0) for i in range(7)] + [(4.0 * i, 4.0) for i in range(1, 6)]
J = {name: k for k, name in enumerate(names)}
pairs = ["L0 L1", "L1 L2", "L2 L3", "L3 L4", "L4 L5", "L5 L6", "U1 U2", "U2 U3", "U3 U4", "U4 U5",
         "L1 U1", "L2 U2", "L3 U3", "L4 U4", "L5 U5", "L0 U1", "L6 U5", "U1 L2", "U2 L3", "U5 L4", "U4 L3"]
members = [(J[p.split()[0]], J[p.split()[1]]) for p in pairs]
loads = {J[f"L{i}"]: (0.0, -50e3) for i in range(1, 6)}        # N
E, A = 210e9, [3.0e-3] * len(members)                          # Pa, m^2 (3000 mm^2 everywhere)

u, N, R, K = truss_fem(nodes, members, [(J["L0"], 0), (J["L0"], 1), (J["L6"], 1)], loads, E, A)
print(f"stiffness matrix {K.shape[0]} x {K.shape[1]}, symmetric: {np.allclose(K, K.T)}, "
      f"rank without supports {np.linalg.matrix_rank(K)} (3 rigid-body motions)")
kN = lambda force: round(force / 1e3, 3) + 0.0              # in kN, without a "-0.0"
print(f"reactions: L0 ({kN(R[J['L0'], 0]):.1f}, {kN(R[J['L0'], 1]):.1f}) kN, L6 {kN(R[J['L6'], 1]):.1f} kN")
print(f"mid-span deflection at L3: {u[J['L3'], 1] * 1e3:.1f} mm (span / {24 / abs(u[J['L3'], 1]):.0f})")
print(f"roller at L6 moves {u[J['L6'], 0] * 1e3:.1f} mm sideways")
for p in ["L0 L1", "L1 U1", "L2 L3", "U2 U3", "U2 L3", "L3 U3", "L0 U1"]:
    print(f"  {p.replace(' ', '-'):6} {kN(N[pairs.index(p)]):8.1f} kN")

# The equilibrium-matrix solver of the trusses lesson gives the same member forces?
Am = np.zeros((24, 24))
Pn = np.asarray(nodes)
for e, (a, b) in enumerate(members):
    d = (Pn[b] - Pn[a]) / np.linalg.norm(Pn[b] - Pn[a])
    Am[2*a:2*a + 2, e] += d
    Am[2*b:2*b + 2, e] -= d
for k, (node, dof) in enumerate([(J["L0"], 0), (J["L0"], 1), (J["L6"], 1)]):
    Am[2*node + dof, 21 + k] = 1.0
F = np.zeros(24)
for node, (fx, fy) in loads.items():
    F[2*node:2*node + 2] = fx, fy
x = np.linalg.solve(Am, -F)
print("same member forces as the equilibrium solver (to 1e-6 N):", np.allclose(x[:21], N, rtol=0, atol=1e-6))

# Pin both ends: statically indeterminate, which the equilibrium solver could not do
u2, N2, R2, _ = truss_fem(nodes, members, [(J["L0"], 0), (J["L0"], 1), (J["L6"], 0), (J["L6"], 1)],
                          loads, E, A)
print(f"\nboth ends pinned: horizontal reactions {kN(R2[J['L0'], 0]):.1f} and {kN(R2[J['L6'], 0]):.1f} kN")
print(f"  bottom chord L2-L3 {kN(N2[pairs.index('L2 L3')]):.1f} kN (was {kN(N[pairs.index('L2 L3')]):.1f}), "
      f"mid-span deflection {u2[J['L3'], 1] * 1e3:.1f} mm")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The member forces are exactly those of the trusses lesson: 125 kN in L0L1L_0L_1, 200 kN in L2L3L_2L_3, −225-225 kN in U2U3U_2U_3, 35.4 kN in the diagonal U2L3U_2L_3, zero in L3U3L_3U_3, and −176.8-176.8 kN in the end posts, and they agree with the equilibrium solver to within a millionth of a newton. For a determinate truss, member forces do not depend on stiffness at all; what the stiffness method adds is the displacements: the bridge sags 15.2 mm at mid-span (span/1584), and the roller end slides 5.7 mm outwards as the bottom chord stretches. The stiffness matrix is symmetric, and without supports its rank is 21 of 24, one missing for each rigid-body motion in the plane (two translations and a rotation).

Pinning both ends makes the truss indeterminate. The supports now stop the bottom chord from lengthening, and each pushes inwards with 150 kN. That thrust takes 150 kN out of every bottom-chord member, so L2L3L_2L_3 drops from 200 to 50 kN, and the mid-span deflection falls to 11.3 mm. The price is that the abutments must now resist a large horizontal force, and the answer depends on their stiffness and on temperature: a hot day that lengthens the chord would push on them too.

DefinitionsH

Beam, plane and solid elements in outline

Beam elements. A beam's nodes carry a deflection vv and a rotation θ\theta, because bending needs slope continuity between elements. Interpolating with cubic (Hermite) polynomials and integrating the bending energy 12∫EI (v′′)2 dx\tfrac12\int EI\,(v'')^2\,dx gives the element stiffness matrix for a beam element of length hh,

ke=EIh3(126h−126h6h4h2−6h2h2−12−6h12−6h6h2h2−6h4h2),\mathbf{k}_e = \frac{EI}{h^3}\begin{pmatrix} 12 & 6h & -12 & 6h \\ 6h & 4h^2 & -6h & 2h^2 \\ -12 & -6h & 12 & -6h \\ 6h & 2h^2 & -6h & 4h^2 \end{pmatrix},

acting on (v1,θ1,v2,θ2)(v_1, \theta_1, v_2, \theta_2). A distributed load is turned into consistent nodal forces and moments. Adding the bar element's axial stiffness gives a frame element with three degrees of freedom per node in 2-D (six in 3-D), the workhorse of structural frame analysis.

python
import numpy as np

def beam_fem(x, EI, supports, point_loads=(), w=lambda xm: 0.0):
    """Euler-Bernoulli beam with cubic (Hermite) elements between nodes x.
    Two dofs per node: deflection v and rotation theta. supports: list of (node, dof) held at 0.
    point_loads: list of (node, force); w(x): distributed load per length (upwards +), applied
    as consistent nodal loads with the element's mid-point value. Returns v, theta, reactions."""
    n = len(x)
    K = np.zeros((2 * n, 2 * n))
    f = np.zeros(2 * n)
    for e in range(n - 1):
        h = x[e + 1] - x[e]
        k = EI / h**3 * np.array([[12, 6*h, -12, 6*h],
                                  [6*h, 4*h*h, -6*h, 2*h*h],
                                  [-12, -6*h, 12, -6*h],
                                  [6*h, 2*h*h, -6*h, 4*h*h]])
        q = w((x[e] + x[e + 1]) / 2)
        fe = q * np.array([h / 2, h * h / 12, h / 2, -h * h / 12])    # consistent nodal loads
        d = slice(2 * e, 2 * e + 4)
        K[d, d] += k
        f[d] += fe
    for node, P in point_loads:
        f[2 * node] += P
    fixed = [2 * node + dof for node, dof in supports]
    free = [i for i in range(2 * n) if i not in fixed]
    u = np.zeros(2 * n)
    u[free] = np.linalg.solve(K[np.ix_(free, free)], f[free])
    R = K @ u - f
    return u[0::2], u[1::2], R[0::2]

# 1. Cantilever, 2 m, 5 kN at the tip: ONE element reproduces P L^3 / (3 EI) exactly
EI = 210e9 * 7.59e-5
v, th, R = beam_fem(np.array([0.0, 2.0]), EI, [(0, 0), (0, 1)], [(1, -5e3)])
print(f"cantilever, 1 element: tip {v[-1] * 1e3:.4f} mm, formula {-5e3 * 8 / (3 * EI) * 1e3:.4f} mm")

# 2. Propped cantilever, 4 m, 6 kN/m: prop force 3wL/8 = 9 kN (the deflection lesson)
x = np.linspace(0.0, 4.0, 5)
v, th, R = beam_fem(x, 1e6, [(0, 0), (0, 1), (4, 0)], w=lambda xm: -6e3)
print(f"propped cantilever, 4 elements: prop force {R[-1] / 1e3:.3f} kN")

# 3. The statics beam with three supports: pin at 0, rollers at 3.5 m and 5 m, overhang to 6 m;
#    6.93 kN down at 2 m and 2 kN/m from 3 m to 6 m. Nodes every 0.5 m.
x = np.linspace(0.0, 6.0, 13)
node = {round(xi, 6): i for i, xi in enumerate(x)}
v, th, R = beam_fem(x, 210e9 * 7.856e-6, [(node[0.0], 0), (node[3.5], 0), (node[5.0], 0)],
                    [(node[2.0], -8e3 * np.cos(np.radians(30)))],
                    w=lambda xm: -2e3 if xm > 3.0 else 0.0)
print(f"three-support beam: reactions {R[node[0.0]] / 1e3:.2f}, {R[node[3.5]] / 1e3:.2f}, "
      f"{R[node[5.0]] / 1e3:.2f} kN; largest sag {-v.min() * 1e3:.2f} mm at a node")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

One cubic element reproduces the cantilever formula PL3/(3EI)PL^3/(3EI) exactly, because the exact deflection of a beam with only end loads is a cubic. Four elements give the propped cantilever's 9 kN prop force, and the 6 m beam on three supports from the deflection lesson comes out with the same reactions computed there by superposition: 2.06, 8.99 and 1.88 kN. The largest nodal sag is 2.11 mm; the true maximum, 2.16 mm, lies between nodes, a reminder that results are reported where the mesh has points.

Plane and solid elements. For a plate in its own plane (plane stress) or a long body in cross-section (plane strain), the simplest element is the three-node constant-strain triangle: linear displacements, so constant strain and stress in each element. Four-node quadrilaterals, six-node triangles with quadratic shapes, and in three dimensions four- and ten-node tetrahedra and eight- and twenty-node hexahedra follow the same pattern, with the stiffness integrals evaluated numerically (Gauss quadrature) on a mapped reference element. Shell elements model thin-walled parts such as car bodies and aircraft skins efficiently, with rotations as well as displacements at each node.

ComputationC

Meshing, convergence and verification

A finite element answer is an approximation whose quality depends on the mesh. The fix is a convergence study: solve on successively finer meshes (h-refinement) or with higher-order elements (p-refinement) and watch the quantity you care about settle. The block below models a steel cantilever 1 m long and 100 mm deep in plane stress with constant-strain triangles, and compares its tip deflection with beam theory including shear deformation.

python
import numpy as np

# A steel cantilever 1 m long, 0.1 m deep, 0.01 m thick, modelled in 2-D plane stress with
# constant-strain triangles (CST), clamped at x = 0, with P shared among the tip nodes.
E, nu, L, H, t, P = 210e9, 0.3, 1.0, 0.1, 0.01, -1e3
D = E / (1 - nu**2) * np.array([[1, nu, 0], [nu, 1, 0], [0, 0, (1 - nu) / 2]])

def cantilever_cst(nx, ny):
    xs, ys = np.linspace(0, L, nx + 1), np.linspace(-H / 2, H / 2, ny + 1)
    X, Y = np.meshgrid(xs, ys, indexing="ij")
    xy = np.column_stack([X.ravel(), Y.ravel()])
    idx = lambda i, j: i * (ny + 1) + j
    tris = []
    for i in range(nx):
        for j in range(ny):                         # each rectangle split into two triangles
            a, b, c, d = idx(i, j), idx(i + 1, j), idx(i + 1, j + 1), idx(i, j + 1)
            tris += [(a, b, c), (a, c, d)]
    K = np.zeros((2 * len(xy), 2 * len(xy)))
    for tri in tris:
        (x1, y1), (x2, y2), (x3, y3) = xy[list(tri)]
        area = 0.5 * ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1))
        bb = np.array([y2 - y3, y3 - y1, y1 - y2]) / (2 * area)
        cc = np.array([x3 - x2, x1 - x3, x2 - x1]) / (2 * area)
        B = np.zeros((3, 6))                        # strains from the six nodal displacements
        B[0, 0::2], B[1, 1::2] = bb, cc
        B[2, 0::2], B[2, 1::2] = cc, bb
        dofs = np.ravel([[2 * n, 2 * n + 1] for n in tri])
        K[np.ix_(dofs, dofs)] += t * area * B.T @ D @ B
    f = np.zeros(2 * len(xy))
    tip = [idx(nx, j) for j in range(ny + 1)]
    share = np.full(ny + 1, 1.0 / ny)
    share[[0, -1]] /= 2                             # end nodes carry half a share
    f[[2 * n + 1 for n in tip]] = P * share
    fixed = {d for j in range(ny + 1) for d in (2 * idx(0, j), 2 * idx(0, j) + 1)}
    free = [d for d in range(2 * len(xy)) if d not in fixed]
    u = np.zeros(2 * len(xy))
    u[free] = np.linalg.solve(K[np.ix_(free, free)], f[free])
    return u[[2 * n + 1 for n in tip]].mean(), len(free)

I, G = t * H**3 / 12, E / (2 * (1 + nu))
beam = P * L**3 / (3 * E * I) + P * L / (5 / 6 * G * t * H)    # bending + shear deflection
print(f"beam theory (with shear): tip deflection {beam * 1e3:.3f} mm")
print(" mesh       unknowns   tip deflection   fraction of beam theory")
for nx, ny in [(10, 1), (20, 2), (40, 4), (80, 8)]:
    v, n = cantilever_cst(nx, ny)
    print(f" {nx:3d} x {ny:<2d}   {n:7d}      {v * 1e3:7.3f} mm        {v / beam:6.3f}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The coarsest mesh, one row of 20 triangles through the depth, gives less than a quarter of the true deflection; even 1440 unknowns give only 95%. Constant-strain triangles cannot bend: inside each one the strain is uniform, so representing the linear strain through a beam's depth takes many rows, and a coarse mesh locks, stiff and wrong. The errors (77%, 46%, 18%, 5.4%) shrink by factors of 1.7, 2.6 and 3.3, approaching the factor of 4 of the method's asymptotic rate only on the finest meshes. A user who stopped at the second mesh, which "looks reasonable", would have been out by half. The professional remedies are quadratic elements, which bend well with one or two through the depth, or finer meshes where the stresses change fastest.

Verification and validation are different questions. Verification asks whether the equations are solved correctly: convergence studies, checks against exact solutions and published benchmarks (NAFEMS maintains a widely used set), and simple sanity checks. Validation asks whether the equations are the right ones for the real part: comparison with strain-gauge measurements, load tests and service experience. The ASME V&V 10 standard and NAFEMS publications describe the process. Every model should pass a checklist before anyone trusts it:

  • the reactions add up to the applied loads (the statics lesson's free-body diagram, done by hand);
  • the deflected shape looks physically sensible, with displacements of a plausible size;
  • a hand calculation with this level's formulas agrees in order of magnitude;
  • the stresses at the points that matter have converged;
  • the units are consistent throughout.
geometry(CAD)meshmaterials, loads,supportssolveK u = fdisplacements,stressescheck: reactions, convergence,hand calculation, testrevise
The finite element workflow. Pre-processing builds the model from the geometry; the solver assembles and solves K u = f; post-processing turns displacements into stresses. Checks against hand calculations, convergence studies and tests send the analyst back to the model far more often than to the solver.
ExplanationH

Finite element software

Industrial analysis runs on large commercial suites from companies in the United States, France, Germany, Sweden, Korea and elsewhere, which add libraries of elements and materials, contact, nonlinear and dynamic solvers, and links to CAD; aerospace and automotive work relies heavily on Nastran-family solvers and on general-purpose nonlinear codes, and crash simulation on explicit dynamics codes. A strong open-source ecosystem is used in industry, research and teaching: CalculiX (driven from FreeCAD's FEM workbench), EDF's code_aster, Finland's Elmer, the FEniCS Project for writing your own formulations from Python, and the mesh generator Gmsh.

A model starts from geometry and a mesh. Here is a Gmsh script for a quarter of a plate with a central hole, using symmetry to model a quarter of the plate, with small elements at the hole where the stress concentration of Failure and fatigue lives (a mesher's input file, shown for its structure; not run here):

text
// Quarter of a 200 x 100 mm plate with a 20 mm hole (Gmsh .geo). Not run here.
lc = 5.0;                        // element size far from the hole, mm
lh = 0.5;                        // element size at the hole, mm
Point(1) = {10, 0, 0, lh};
Point(2) = {100, 0, 0, lc};
Point(3) = {100, 50, 0, lc};
Point(4) = {0, 50, 0, lc};
Point(5) = {0, 10, 0, lh};
Point(6) = {0, 0, 0, lh};        // centre of the hole
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 5};
Circle(5) = {5, 6, 1};           // quarter circle: start, centre, end
Curve Loop(1) = {1, 2, 3, 4, 5};
Plane Surface(1) = {1};
Physical Curve("symmetry_v_fixed") = {1};
Physical Curve("symmetry_u_fixed") = {4};
Physical Curve("loaded_edge") = {2};
Physical Surface("plate") = {1};
Mesh.ElementOrder = 2;           // quadratic triangles

The symmetry edges become boundary conditions (no displacement across the plane of symmetry), the loaded edge receives the tension, and the solver reports the peak stress at the hole, which for a plate this narrow should come out a little above the wide-plate value of three times the remote stress. Today's frontier, the subject of Simulation-driven design, turns this around: topology optimisation lets the finite element model decide where material should go, and surrogate models trained on many simulations explore designs faster than the solver alone.

ExplanationH

What can go wrong: garbage in, garbage out

A finite element program will produce beautiful colour plots from any model, right or wrong. The common errors are mundane:

  • Units. Mixing millimetres with metres or MPa with Pa gives answers off by thousands. A consistent set (N, mm, MPa, tonnes, s; or N, m, Pa, kg, s) must be used everywhere.
  • Boundary conditions. Real supports are neither perfectly fixed nor perfectly free. Fully clamping a bolted flange makes it too stiff and creates false stress peaks at the clamp; too few restraints leave a rigid-body motion and a singular matrix.
  • Loads. A wrong load case, a point load where the real load is spread, a missing self-weight or thermal load.
  • Elements and mesh. Linear triangles and tetrahedra locking in bending; badly distorted elements; a mesh too coarse at the stress concentration.
  • Physics left out. Linear analysis assumes small deflections, linear material and fixed contact. Plasticity, large deflections, contact that opens and closes, and buckling need nonlinear analysis.

The most quoted example is the Sleipner A offshore platform in Norway. In 1991 its concrete base, under construction, sank during a controlled ballasting test in a fjord near Stavanger; no one was hurt, but the loss was enormous. The investigations found that the shear forces in some cell walls had been underestimated by roughly 45 per cent, partly because of poorly shaped elements in the finite element model, and that reinforcement in those walls was inadequately anchored. A hand check of those walls would have flagged it. The replacement structure was analysed again with independent checks, and the case is still taught as a warning about trusting software without verification.

History & global context

From aircraft wings to every product

Alexander Hrennikoff (1941) modelled elastic plates as lattices of bars, and Richard Courant (1943) solved a torsion problem with piecewise-linear functions on triangles. In the 1950s aircraft engineers needed stiffness models of swept wings: John Argyris in London developed matrix energy methods, and at Boeing, M. J. Turner, R. W. Clough, H. C. Martin and L. J. Topp published in 1956 the stiffness analysis of complex structures with triangular plate elements, the paper usually taken as the method's start. Clough named it the finite element method in 1960. Olgierd Zienkiewicz's 1967 textbook spread it far beyond aerospace; mathematicians, notably in France and the United States, put its convergence on a firm footing in the 1970s; and NASA's NASTRAN program, released around 1970, began the era of general-purpose software. In China, Feng Kang developed a closely related method independently in the 1960s for the design of dams.

Common misconceptionsH

Common misconceptions

Misconception

"A finer mesh is always more accurate." Usually, but not at a singularity, where refinement makes the reported peak grow without limit, and not if the model's physics or boundary conditions are wrong: a very fine mesh of the wrong problem is precisely wrong.

Misconception

"FEA results are exact because the computer solved the equations exactly." The linear solve is exact to rounding error, but it solves an approximate problem: idealised geometry, supports and loads, simplified material behaviour and a finite mesh.

Misconception

"Hand calculations are obsolete." They are how models are checked. The reactions, the order of magnitude of the stresses and deflections, and the location of the peak should all be predictable from this level's formulas before the solver runs.

Misconception

"The red spot on the contour plot is where the part will fail." It is where the computed stress is highest, which may be a singularity at an idealised corner or support. Whether the part fails there depends on the real geometry, the failure mode and, for repeated loads, fatigue.

Exercises

Exercises

1. The finite element method

Warm-upHuman

A plane truss has 12 joints and 21 members. It rests on a pin (which stops both displacements of its joint) and a roller (which stops one). How many unknown nodal displacements does a finite element solver solve for?

2. The finite element method

CoreHuman

Two bar elements are joined end to end along a line: element 1 between nodes 1 and 2 with stiffness k1=300k_1 = 300 kN/mm, and element 2 between nodes 2 and 3 with k2=100k_2 = 100 kN/mm. Node 1 is fixed. A load of 30 kN acts at node 2 and 60 kN at node 3, both pulling along the bar away from the support. What is the displacement of node 3, in micrometres?

3. The finite element method

CoreHuman

You build a plane truss model and the solver stops with "singular stiffness matrix". The truss is a rigid triangle of three members. Which support arrangement explains the error?

Choose one

4. The finite element method

CoreHuman

An L-shaped steel bracket has a perfectly sharp inside corner in your model. Refining the mesh at the corner, you get peak von Mises stresses of 210, 260, 330 and 420 MPa. What should you conclude?

Choose one

5. The finite element method

Warm-upHuman

Which of these are verification activities (checking that the equations are solved correctly), rather than validation (checking that they are the right equations for the real part)? Select all that apply.

Choose all that apply

6. The finite element method

CoreComputational

Write truss_element_stiffness(xa, ya, xb, yb, E, A) that returns the 4 × 4 stiffness matrix (a NumPy array) of a plane truss element from node aa at (xa,ya)(x_a, y_a) to node bb at (xb,yb)(x_b, y_b), with Young's modulus E and area A, acting on the displacements (ua,va,ub,vb)(u_a, v_a, u_b, v_b):

ke=EAL ttT,t=(−c,−s,c,s),\mathbf{k}_e = \frac{EA}{L}\,\mathbf{t}\mathbf{t}^\mathsf{T}, \qquad \mathbf{t} = (-c, -s, c, s),

where LL is the element's length and (c,s)(c, s) the unit vector from aa to bb.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

7. The finite element method

StretchComputational

Write a tiny one-dimensional finite element solver, solve_springs(n_nodes, springs, fixed, loads):

  • springs is a list of (i, j, k): a spring (or bar element) of stiffness k between nodes i and j;
  • fixed is a list of node indices whose displacement is zero;
  • loads is a sequence of n_nodes applied nodal forces.

Assemble the global stiffness matrix, solve for the displacements of the free nodes, and return a pair of NumPy arrays (u, R) of length n_nodes: the displacements, and the reactions (K @ u - loads, which is non-zero only at fixed nodes). Springs may be in series or in parallel, and the structure may be statically indeterminate.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Further reading and resources

  • Variational methods for the solution of problems of equilibrium and vibrations · Richard Courant · 1943The lecture, in the Bulletin of the American Mathematical Society, that used piecewise-linear functions on triangles, an early form of the method.
  • The Finite Element Method · O. C. Zienkiewicz, R. L. Taylor and J. Z. ZhuThe classic textbook, first published by Zienkiewicz and Cheung in 1967 and revised in many editions.
  • CalculiXA free, open-source finite element program for structural and thermal analysis, used as the solver of FreeCAD's FEM workbench.
  • FreeCADOpen-source parametric CAD with a finite element workbench.
  • GmshAn open-source three-dimensional mesh generator with a built-in CAD engine and scripting language.
  • FEniCS ProjectOpen-source software for solving partial differential equations by the finite element method from Python.
  • code_asterEDF's open-source structural mechanics finite element software.
  • NAFEMSThe international association for engineering modelling, analysis and simulation; publishes benchmarks and guidance on verification and validation.
  • ASMEPublishes the V&V 10 standard on verification and validation in computational solid mechanics.