You have a curve you want a neural network to fit. Adding hidden units seems to help, but it is useful to know whether this kind of network can represent the curve at all, before spending time on the training settings. The Universal Approximation Theorem gives an existence result for continuous functions on a closed, bounded region. With enough suitable nonlinear units, even one hidden layer can approximate such a function as closely as you choose.
We fit the three-sine curve in NumPy to test that extra capacity. Widening the ReLU layer from one unit to 256 adds kinks to the fit. MSE falls from 0.54 to 0.0025, but training must still find weights that use the available capacity.
Let's Build It
Open this in Google Colab and run it top to bottom. It fits a deliberately wiggly target with one-hidden-layer networks of increasing width, and prints how the error shrinks.
Watch the fit tighten as we add hidden units. At width 1 the network is a single sloped line; by width 256 it traces every wiggle.

Here is the whole thing. One target function, one network class, one fit routine.
import numpy as np
import torch
import torch.nn as nn
def target(x):
"""A continuous but wiggly target: three stacked sine waves on [-1, 1]."""
return (np.sin(2 * np.pi * x)
+ 0.5 * np.sin(6 * np.pi * x)
+ 0.25 * np.sin(10 * np.pi * x))
class OneHiddenLayer(nn.Module):
"""One hidden layer: f(x) = W2 · act(W1 · x + b1) + b2, `width` units."""
def __init__(self, width, act="relu"):
super().__init__()
self.fc1 = nn.Linear(1, width)
self.fc2 = nn.Linear(width, 1)
self.act = torch.relu if act == "relu" else torch.tanh
def forward(self, x):
return self.fc2(self.act(self.fc1(x)))
def fit(width, x, y, act="relu", restarts=6, rounds=15):
"""Fit the width-`width` net; keep the best of several random restarts.
Restarts separate the network's approximation *capacity* from the luck of
one optimiser run, so the error reflects what the architecture can
represent, not where a single gradient descent happened to land.
"""
xt = torch.tensor(x, dtype=torch.float32).view(-1, 1)
yt = torch.tensor(y, dtype=torch.float32).view(-1, 1)
loss_fn = nn.MSELoss()
best_net, best_mse = None, float("inf")
for s in range(restarts):
torch.manual_seed(1000 * s + width)
net = OneHiddenLayer(width, act)
opt = torch.optim.LBFGS(net.parameters(), lr=0.8, max_iter=50,
line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = loss_fn(net(xt), yt)
loss.backward()
return loss
for _ in range(rounds):
opt.step(closure)
with torch.no_grad():
mse = loss_fn(net(xt), yt).item()
if mse < best_mse:
best_net, best_mse = net, mse
return best_net, best_mse
x = np.linspace(-1, 1, 400)
y = target(x)
for w in [1, 4, 16, 256]:
_, mse = fit(w, x, y)
print(f"width {w:>3}: MSE {mse:.2e}")
You should see the error fall by more than two orders of magnitude:
width 1: MSE 5.43e-01
width 4: MSE 1.85e-01
width 16: MSE 8.92e-02
width 256: MSE 2.52e-03
The same four widths, plotted, tell the story at a glance. One unit can only draw a line. Four units bend it a few times. Sixteen units capture the envelope. Two hundred and fifty-six units trace the fine ripples.

You just built a universal approximator. Now let us understand why it works.
What Just Happened?
The network is deliberately shallow: an input, one hidden layer of width units, and a scalar output. Written out, it computes
where is the width, is the activation (ReLU or tanh here), and are the weights and biases the optimiser learns. Every hidden unit takes the input, scales and shifts it (), squashes it through , and the output layer adds the results up with its own weights. That sum is the entire model. The theorem claims this one sum, made wide enough, gets arbitrarily close to any continuous target.
The fit routine trains each network with L-BFGS, a second-order optimiser that converges cleanly on tiny problems like this one. It runs several random restarts and keeps the best, because we want to measure what a width- network can represent, not where one unlucky initialisation stalled. That distinction (capacity versus optimisation) returns later.
A sigmoid is a soft step
To see why the sum works, look at one hidden unit. A sigmoid is a soft step: it rises from 0 to 1 around , and the weight controls how sharp the transition is. Crank up and the soft step becomes a hard one.
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
xg = np.linspace(-1, 1, 800)
for steep in [3, 10, 60]:
step = sigmoid(steep * xg) # a soft step at x = 0
Now put two soft steps back to back and subtract them. A step that rises at minus a step that rises at leaves a localised bump: roughly zero outside , roughly one inside.

def bump(xg, a, b, s=120.0):
"""A localised bump on [a, b] from two opposing soft steps."""
return sigmoid(s * (xg - a)) - sigmoid(s * (xg - b))
That bump is the atom of the whole construction. One hidden unit gives you a soft step; a pair of them gives you a bump you can place anywhere and scale to any height.
Bumps tile any curve
Once you can make a bump of any height at any location, approximating a curve is bookkeeping. Chop the domain into narrow strips. On each strip, add a bump whose height equals the target's value there. Stack enough thin bumps and their sum traces the curve as closely as you like. This is exactly what a wide hidden layer does: each unit owns a slice of the input, and the output layer sets each slice's height.
K = 40
edges = np.linspace(-1, 1, K + 1)
centres = 0.5 * (edges[:-1] + edges[1:])
approx = sum(target(c) * bump(xg, a, b)
for c, a, b in zip(centres, edges[:-1], edges[1:]))
![Forty narrow orange bumps, each scaled to the target's height at its location, summing into a blue curve that closely tracks the grey wiggly target across [-1, 1].](/images/posts/universal-approximation-theorem-from-scratch-sum-of-bumps.webp)
We never trained this. We placed the bumps by hand and the sum already matches the target. That is the constructive heart of the proof: a network that approximates the curve exists, and here it is. Training is just a way to discover such a network automatically instead of hand-placing 40 bumps.
ReLU: a piecewise-linear tiling
The networks we trained use ReLU, , not sigmoids. ReLU tells the same story in straight lines. Each ReLU unit is off (flat zero) until its input crosses a threshold, then switches on as a ramp. Add up ramps that switch on at different points and you get a piecewise-linear function: straight segments joined at kinks, one kink per active unit. A ReLU network with units draws a curve out of at most line segments.

Twelve segments only rough out the target. This is the picture behind the width sweep: more units mean more kinks, more kinks mean finer segments, and finer segments mean a closer fit. Sigmoids tile a curve with bumps; ReLUs tile it with hinges. Either way, width buys resolution.
Going Deeper
The theorem, stated
Cybenko's 1989 result is a density statement. Let be a continuous sigmoidal function (it tends to 0 as its input goes to and to 1 as it goes to ). Then finite sums of the form above are dense in the space of continuous functions on the unit cube . Concretely, for any continuous target and any tolerance , there is a width and a set of weights such that
Read the pieces. The is the worst-case gap between network and target over the whole region: the bound holds everywhere, not just on average. is your accuracy budget, and you may set it as small as you like. The price is : tighter tolerance needs more hidden units. The theorem promises the network exists. It says nothing about how big has to be, and nothing about how to find the weights.
Error versus width
The experiment turns that abstract promise into a curve. Fit the target at every width from 1 to 256 and plot the error. For ReLU units the approximation error falls almost exactly like : double the width, roughly halve the error. Smooth tanh units are even more efficient on this smooth target, reaching the noise floor with fewer units.

The straight-line decay on log-log axes is the theorem made visible: there is no floor the error refuses to cross, no width past which adding units stops helping. Keep widening and the error keeps falling. That is what "arbitrary accuracy" looks like on a chart.
Existence is not learnability
Look again at the tanh curve. It reaches its best value around width 128 and then wobbles slightly upward at 256. A wider network can only represent the target better, so this is not a capacity limit. It is the optimiser failing to find the better weights that provably exist. Wide tanh networks are harder to train: units saturate, gradients flatten, and even L-BFGS with six restarts sometimes settles for a worse basin.
This gap is the theorem's fine print. Universal approximation is an existence result. It guarantees a good network is out there; it does not guarantee gradient descent will land on it, and it does not tell you how much data you need to pin the weights down. In practice the bottleneck is almost never representational capacity. It is optimisation (which optimiser, which learning rate), conditioning (tricks like batch normalisation), and generalisation. Capacity is the easy part; the theorem hands it to you for free.
Depth, width, and parameter efficiency
If one hidden layer already approximates anything, why does every modern network go deep? Because "possible" and "efficient" are different questions. The classic theorem is about width, and width pays a steep price: matching a complicated function with a single layer can demand an astronomical number of units. Depth is far cheaper. A ReLU network carves its input into linear regions, and the maximum number of regions a network can produce grows only polynomially with width but exponentially with depth (Montúfar and colleagues, 2014). Stacking layers composes simple foldings into intricate ones, so a deep narrow network can express patterns that would need an impractically wide shallow one. Lu and colleagues (2017) proved the mirror image: there are also functions a narrow-enough network cannot represent no matter how deep, so width and depth trade off against each other. The 1989 theorem tells you a shallow net can do the job; the modern expressivity results tell you why nobody builds them that way.
Beyond one dimension
None of this is special to curves on a line. The same construction works in any number of input dimensions, tiling the space with multidimensional bumps or hinges. Swap the input layer for two inputs and fit a two-dimensional surface, a checkerboard, with the identical one-hidden-layer recipe.

Eight units cut the plane into a handful of wedges and miss the pattern entirely. Two hundred and fifty-six units recover the full checkerboard. Width buys resolution in two dimensions exactly as it did in one.
When the theorem does not save you
Universality is a weaker guarantee than it sounds, and leaning on it too hard leads to three mistakes. First, it is about a compact region: nothing is promised about how the network behaves outside the range it saw, so extrapolation is not covered. Second, the required width can explode with input dimension, the curse of dimensionality, so "finite " can still mean "more units than atoms in the universe" for a rich function in high dimensions. Third, fitting the training points is not the goal; generalising to new ones is. A network wide enough to interpolate any target is also wide enough to memorise noise, which is why regularisation and validation matter more than raw capacity. The theorem removes one worry (can the model represent this?) and leaves the hard ones (can we train it, and will it generalise?) firmly in place.
Where This Comes From
The result arrived from three groups at once. George Cybenko (1989), in "Approximation by Superpositions of a Sigmoidal Function", proved density for continuous sigmoidal activations using a clever functional-analysis argument (the Hahn-Banach theorem plus properties of signed measures) rather than the constructive bump-stacking we used for intuition. In the same year, Hornik, Stinchcombe and White (1989), in "Multilayer Feedforward Networks are Universal Approximators", reached the same conclusion by a different route and stated the punchline plainly:
"Standard multilayer feedforward networks are capable of approximating any measurable function to any desired degree of accuracy... In this sense, multilayer feedforward networks are a class of universal approximators."
Their framing matters. As they put it, any failure of a network to fit a function must be blamed on training, not on the architecture:
"Failures can be attributed to inadequate learning, insufficient numbers of hidden units, or the lack of a deterministic relationship between input and target."
Hornik (1991) then showed the sigmoid was a red herring: what makes the construction work is the activation being bounded and non-constant, not its particular S-shape. Leshno, Lin, Pinkus and Schocken (1993) sharpened this to its final form. A feedforward network with a locally bounded activation is a universal approximator if and only if the activation is non-polynomial. That single condition is why ReLU, tanh, sigmoid, GELU and Swish all work, and why a polynomial activation would not: a network of polynomials is just a polynomial of bounded degree, which cannot approximate everything.
For a picture-first version of the bump argument, Michael Nielsen's chapter "A visual proof that neural nets can compute any function" walks through the same soft-step-to-bump construction interactively. For the depth side of the story, Montúfar and colleagues' "On the Number of Linear Regions of Deep Neural Networks" (2014) and Lu and colleagues' "The Expressive Power of Neural Networks: A View from the Width" (2017) explain why practitioners trade width for depth.
The lineage explains why the Reddit question never dies. Universal approximation is not a property of multilayer perceptrons in particular; it is a property most flexible model classes share. Kernel machines, sufficiently deep decision-tree ensembles like random forests and boosting, and transformers all come with their own universal-approximation theorems, each a descendant of these 1989 papers. When a new architecture lands and someone asks "but is it a universal approximator?", they are asking whether it has earned a place in this family. Usually it has, and usually that was never the interesting question.
Interactive Tools
- Overfitting Explorer: the width sweep from the other side: watch capacity turn from underfitting into memorising noise, and see why universal approximation is not the same as generalisation.
- Regression Playground: fit polynomials of growing degree to your own points and feel the same capacity-versus-fit trade-off a wider hidden layer gives you.
- GP Regression Playground: Gaussian processes are another universal function approximator, non-parametric rather than a fixed-width network, with uncertainty bands built in.
Related Posts
- Backpropagation from First Principles: how the weights in these networks are learned, derived from the chain rule.
- SGD, Momentum, and Adam: Optimisers from First Principles: the learnability side of the story, since finding the network the theorem guarantees is an optimisation problem.
- Batch Normalisation from Scratch: one of the tricks that makes wide and deep networks trainable in practice.
- Random Forests from Scratch: Bagging: tree ensembles are universal approximators too, and a vivid reminder that capacity without regularisation memorises noise.
- Stacking and Ensemble Methods in Python: how ensembles build arbitrary functions by adding simple learners, the same "sum of pieces" idea in a different guise.
- Kolmogorov-Arnold Networks in Python: A Curve on Every Edge: the sibling representation theorem, built as a network with a learned spline on every edge and measured against MLPs.






