---
title: Finite elements in one dimension
heading: Weak forms, hat functions and stiffness matrices
eyebrow: A12 · Lesson 49 · Finite elements
xp: 40
---

::: hook
Finite differences replace derivatives with differences on a grid. The **finite element method** takes another route: it looks for the best approximation to the solution among simple functions, such as straight-line pieces between nodes, in the sense of the equation's energy. It handles uneven meshes, layered materials and awkward shapes naturally, which is why commercial field solvers for capacitance, magnetics and heat are almost all finite-element codes. In one dimension the whole method fits on a page, and its matrix turns out to be the nodal-analysis matrix of a resistor ladder.
:::

::: play
- The smooth curve is the exact solution of $-u'' = 1$ with $u(0) = u(1) = 0$, the parabola $\frac{x(1 - x)}{2}$.
- The straight-line pieces are the finite-element solution with N elements. In this problem its values at the nodes are exactly right, and it is wrong only in between.
- Raise N. The readout gives the largest error, at the middle of each element: $\frac{1}{8N^2}$. Doubling N cuts it by four.
:::

```sim plot
view: graph
x: x = 0..1
y: u = 0..0.14
slider: N = 1..10 step 1 = 3
plot: x*(1 - x)/2 | label: exact | samples: 300
plot: floor(x*N)/N*(1 - floor(x*N)/N)/2 + (x - floor(x*N)/N)*N*((floor(x*N)/N + 1/N)*(1 - floor(x*N)/N - 1/N)/2 - floor(x*N)/N*(1 - floor(x*N)/N)/2) | label: finite elements | color: ch3 | samples: 600
readout: largest error = 1/(8*N^2) | digits: 4
```

::: predict
## With linear elements, the error in u falls as $h^2$. How does the error in the slope $u'$ fall?

- [ ] As $h^2$ too
- [x] As h
- [ ] As $h^3$
- [ ] It doesn't fall

::: reveal
As h. Each piece is a straight line, so its slope is constant across the element while the true slope changes, by about $\lvert u''\rvert h$ across the element. Halving the elements halves the slope error but quarters the value error. That matters in field solvers: potentials converge faster than fields.
:::
:::

::: nameit
## The weak form

For $-(ku')' = f$ on (0, L) with $u = 0$ at the ends, multiply by any smooth test function v that is zero at the ends and integrate by parts:

$$\int_0^Lku'v'\,dx = \int_0^Lfv\,dx \quad\text{for every such } v.$$

This **weak form** asks for only one derivative of u, so piecewise-linear functions qualify. For $k > 0$ it's also the condition for u to minimize the energy $\int\left(\frac12ku'^2 - fu\right)dx$.

## Hat functions

Put nodes at $x_0 = 0 < x_1 < \cdots < x_N = L$. The **hat function** $\phi_i$ is 1 at node i, 0 at every other node, and straight in between. Write $u \approx \sum_iU_i\phi_i$ and use each $\phi_j$ as a test function (Galerkin's method). That gives a linear system $KU = F$ with

$$K_{ij} = \int k\phi_i'\phi_j'\,dx, \qquad F_j = \int f\phi_j\,dx.$$

## The element matrices

On one element of length h with constant k, the two hats have slopes $\pm1/h$, so the element contributes $\frac kh\begin{pmatrix}1 & -1\\ -1 & 1\end{pmatrix}$ to K. Adding the elements up (**assembly**) gives a tridiagonal matrix. With a uniform mesh and constant k, an interior row is $\frac kh(-1, 2, -1)$, the same as the finite-difference matrix. A constant f gives $F_j = fh$.

Each element is a conductance $k/h$ between two nodes, so K is exactly the nodal conductance matrix of a resistor ladder, and F is the current injected at each node. Layered materials just change the conductances.

## Accuracy and eigenvalues

With linear elements the error is $O(h^2)$ in u and $O(h)$ in u'. For eigenvalue problems $-u'' = \lambda u$ the method also needs the **mass matrix** $M_{ij} = \int\phi_i\phi_j\,dx$, with element matrix $\frac h6\begin{pmatrix}2 & 1\\ 1 & 2\end{pmatrix}$; solving $KU = \lambda MU$ gives eigenvalues that are always too high, by the Rayleigh quotient argument of lesson 34.
:::

::: example
## Solve $-u'' = 1$ on (0, 1), with zero ends, using two elements.

::: solution
1. **One unknown.** With h = ½ there is one unknown, $U_1$ at x = ½.
2. **Its row of K.** The neighbors' values are fixed at 0, so the row is
   $$\frac{1}{h}(2) = 4$$
3. **Its load.**
   $$\begin{aligned} F_1 &= \int\phi_1\,dx \\ &= h \\ &= \frac12 \end{aligned}$$
4. **Solve.**
   $$4U_1 = \frac12$$
   giving $U_1 = \frac18$.
5. **Compare with the exact solution.** $\frac{x(1 - x)}{2}$ is also $\frac18$ at the midpoint: the nodal value is exact. In one dimension with constant coefficients, linear elements always get the nodal values right for this kind of problem, and the error lives entirely between the nodes.

**Answer:** $U_1 = \frac18$ at x = ½, the exact value.
:::
:::

::: example
## A wall has two layers, each 0.5 m thick, with conductivities 1 and 4 W/(m·K). One face is at 0 °C and the other at 1 °C. What is the temperature at the interface?

::: solution
1. **Element conductances.** Use one element per layer. Their conductances $\frac kh$ are
   $$\begin{aligned} \frac{1}{0.5} &= 2 \\ \frac{4}{0.5} &= 8 \end{aligned}$$
2. **Balance at the interface.** The interface node's equation is the current balance
   $$2(U - 0) + 8(U - 1) = 0$$
   so $U = \frac{8}{10} = 0.8$.
3. **Check with series resistances.** That's exact: heat flows through two thermal resistances in series, 0.5 and 0.125 m²·K/W, so the flux is
   $$\begin{aligned} q &= \frac{1}{0.625}\ \text{W/m}^2 \\ &= 1.6\ \text{W/m}^2 \end{aligned}$$
   and it drops $1.6 \times 0.5 = 0.8$ °C across the first layer.
4. **Why elements handle the jump.** Finite differences across a jump in k need special care; finite elements get it right automatically, because each element keeps its own k.

**Answer:** the interface is at 0.8 °C.
:::
:::

::: example
## Estimate the lowest eigenvalue of $-u'' = \lambda u$ on (0, 1) with fixed ends using four linear elements, and compare with π².

::: solution
1. **The discrete eigenvalue.** For a uniform mesh, the discrete eigenvectors are samples of $\sin\pi x$, and the generalized eigenvalue works out to
   $$\lambda_h = \frac{6}{h^2}\cdot\frac{1 - \cos\pi h}{2 + \cos\pi h}$$
2. **Four elements.** With h = ¼:
   $$\begin{aligned} \lambda_h &= 96 \times \frac{0.2929}{2.7071} \\ &= 10.39 \end{aligned}$$
   against $\pi^2 = 9.870$: 5.2% high.
3. **Lumped mass.** Replacing M by a diagonal "lumped" matrix with h on the diagonal gives the finite-difference value
   $$\frac{4}{h^2}\sin^2\frac{\pi h}{2} = 9.37$$
   5.0% low.
4. **The pattern.** The consistent mass matrix always errs high, as a Rayleigh quotient must, and the errors shrink as $h^2$: with eight elements they are 1.3% each way.

**Answer:** four elements give $\lambda_h = 10.39$, 5.2% above $\pi^2 = 9.870$.
:::
:::

::: check
given: N = 2 | 4 | 8
answer: 6*N^2*(1 - cos(pi/N))/(2 + cos(pi/N))
tolerance: 0.5%

## With {N} equal linear elements (consistent mass), what estimate of the lowest eigenvalue of $-u'' = \lambda u$ on (0, 1) with fixed ends do you get?

::: right
Right. Always above $\pi^2 = 9.870$, approaching it as $h^2$.
:::

::: misses
- [4*N^2*sin(pi/(2*N))^2] That's the lumped mass, the finite-difference value, which lies below $\pi^2$.
- [any] $\lambda_h = \frac{6}{h^2}\cdot\frac{1 - \cos\pi h}{2 + \cos\pi h}$ with $h = 1/N$.
:::
:::

::: check
given: k1 = 1 | 2; k2 = 4 | 8; V = 1 | 10
answer: V*k2/(k1 + k2)
tolerance: 0.5%

## A slab has two layers of equal thickness, with conductivities {k1} and {k2}. Its faces are held at 0 and {V}. With one element per layer, what is the value at the interface?

::: right
Right. Conductances in series: the interface sits at $V\frac{k_2}{k_1 + k_2}$, and it's exact.
:::

::: misses
- [V/2] That would need equal conductivities.
- [V*k1/(k1 + k2)] The poorer conductor takes the larger drop, so the interface sits closer to the far face's value.
- [any] Balance the flows: $\frac{k_1}{h}U = \frac{k_2}{h}(V - U)$.
:::
:::

::: check
given: k = 2 | 5; h = 0.1 | 0.25
answer: 2*k/h
tolerance: 0.5%

## A uniform mesh of linear elements has element length {h} and constant coefficient k = {k}. What is the diagonal entry of K for an interior node?

::: right
Right. Two elements touch each interior node, each adding $\frac kh$.
:::

::: misses
- [k/h] Each interior node belongs to two elements.
- [any] Each element adds $\frac kh$ to both of its nodes' diagonal entries.
:::
:::

::: check
given: h = 0.1 | 0.25; x = 0.5 | 0.75
answer: h*x
tolerance: 0.5%

## For $f(x) = x$ on a uniform mesh with element length {h}, what is the load $F_j = \int f\phi_j\,dx$ at the interior node $x_j$ = {x}?

::: right
Right. The hat is symmetric about $x_j$ and has area h, so a linear f gives $hx_j$.
:::

::: misses
- [h*x/2] The hat spans two elements, so its area is h.
- [any] The hat has area h and is centered on $x_j$.
:::
:::

::: check
kind: parts
given: r = 2..10 int

## A linear-element solution is refined by splitting every element into {r}.

::: part
answer: r^2
tolerance: 0.5%

### By what factor does the largest error in u shrink?

::: misses
- [r] That's for the slope.
- [any] The error in u goes as $h^2$.
:::
:::

::: part
answer: r
tolerance: 0.5%

### And the largest error in u'?

::: misses
- [r^2] The slope converges one order slower.
- [any] The error in u' goes as h.
:::
:::
:::

::: check
kind: choice

## In circuit terms, what is the stiffness matrix of 1D linear elements for $-(ku')' = f$?

- [ ] An impedance matrix of coupled inductors
- [x] The nodal conductance matrix of a ladder of resistors, one per element
- [ ] A matrix of capacitances
- [ ] The incidence matrix of the mesh

::: right
Right. Each element is a conductance $k/h$ between its two nodes, and the load vector is the current injected at each node.
:::

::: misses
- [1] There's no coupling between non-adjacent elements, and nothing stores energy.
- [3] A capacitance matrix appears only for the time-dependent problem, as the mass matrix.
- [4] The incidence matrix is a factor of it: $K = A^TGA$ with G the conductances.
:::
:::

::: check
kind: derivation
vars: f = 0.5..5, L = 0.5..3

## Solve $-u'' = f$ on (0, L) with zero ends using two equal elements.

::: step
answer: 4/L

### What is the stiffness entry of the middle node, $2/h$ with $h = L/2$?
:::

::: step
answer: f*L/2

### What is its load, $fh$?
:::

::: step
answer: f*L^2/8

### What is the computed value at the middle?
:::

::: right
Right. $\frac{fL^2}{8}$, which is the exact midpoint value.
:::
:::

::: check
kind: python

## Write `fem(k, f, N)` that assembles and solves the linear-element system for $-(ku')' = f$ on (0, 1) with zero ends, N equal elements, `k(e)` the coefficient on element e and f a constant. Return the interior nodal values. Set `err` to the largest nodal error for k = 1, f = 1, N = 8 against $\frac{x(1 - x)}{2}$.

```python starter
import numpy as np

def fem(k, f, N):
    return np.zeros(N - 1)

x = np.arange(1, 8) / 8
err = np.max(np.abs(fem(lambda e: 1.0, 1.0, 8) - x * (1 - x) / 2))
print(err)
```

```python solution
import numpy as np

def fem(k, f, N):
    h = 1.0 / N
    K = np.zeros((N - 1, N - 1))
    F = np.zeros(N - 1)
    for e in range(N):
        ke = k(e) / h
        for a in (0, 1):
            i = e - 1 + a
            if 0 <= i < N - 1:
                F[i] += f * h / 2
                for b in (0, 1):
                    j = e - 1 + b
                    if 0 <= j < N - 1:
                        K[i, j] += ke * (1 if a == b else -1)
    return np.linalg.solve(K, F)

x = np.arange(1, 8) / 8
err = np.max(np.abs(fem(lambda e: 1.0, 1.0, 8) - x * (1 - x) / 2))
print(err)
```

```python tests
assert err < 1e-12, f"Linear elements get this problem's nodal values exactly; got an error of {err}."
U = fem(lambda e: 1.0 if e < 2 else 4.0, 1.0, 4)
assert len(U) == 3 and U[1] > U[2], f"With a better conductor on the right, the peak shifts left; got {U}."
```

::: right
Right. The nodal values are exact to rounding, as the first worked example showed, and a layered k just changes each element's conductance.
:::
:::

::: explain
## Why are finite-element eigenvalues always too high?

::: model
The lowest eigenvalue of $-u'' = \lambda u$ is the smallest value of the Rayleigh quotient $\frac{\int u'^2}{\int u^2}$ over all functions that satisfy the boundary conditions, reached only by the true eigenfunction. The finite-element method with a consistent mass matrix minimizes the same quotient, but only over the piecewise-linear functions on the mesh, which is a smaller set. A minimum over a smaller set can't be lower than the minimum over everything, so $\lambda_h \ge \lambda_1$, with equality only if the eigenfunction happened to be piecewise linear. Refining the mesh enlarges the set, so the estimates fall toward the true value from above.
:::
:::

::: practice

::: check
given: N = 2..10 int
answer: 6*N^2*(1 - cos(pi/N))/(2 + cos(pi/N))
tolerance: 0.5%

## Consistent-mass $\lambda_1$ estimate, N = {N}?

::: misses
- [any] $\frac{6}{h^2}\cdot\frac{1 - \cos\pi h}{2 + \cos\pi h}$.
:::
:::

::: check
given: k1 = 3 | 5; k2 = 1 | 2; V = 5 | 12
answer: V*k2/(k1 + k2)
tolerance: 0.5%

## Interface value, conductivities {k1} and {k2}, faces at 0 and {V}?

::: misses
- [any] $V\frac{k_2}{k_1 + k_2}$.
:::
:::

::: check
given: k = 1 | 4; h = 0.05 | 0.5
answer: 2*k/h
tolerance: 0.5%

## Interior diagonal entry, k = {k}, h = {h}?

::: misses
- [any] $\frac{2k}{h}$.
:::
:::
:::
