Mathematical Foundations

I.6 · Mathematical Language

Which curve is which?

Six curves carry most of applied mathematics. Learn to recognise each one, to see what its parameters do, and to know where it stops being defined or stops being computable.

Try it: six families on one plane

Draw these functions

Or start from

Coordinate plane from −7 to 7 on both axes. Vertical scale a is 1 and horizontal shift h is 0. The drawn curves are y equals a times g of x minus h for e to the x, natural log of x, sine of x. A vertical dashed line marks the input x = 1. Values at that input: e to the x: approximately 2.718; natural log of x: exactly 0; sine of x: approximately 0.841.

input
1
shifted input x − h
1
a·e^(x − h)
2.718282
a·ln(x − h)
0
a·sin(x − h)
0.841471

= exact · ≈ rounded to 6 decimals · ⚠ undefined

At x = 1 the highest curve is eˣ (2.718282) and the lowest is ln x (0).

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −6 to 6, up to 2 decimal places

Switch curves on and off, drag the input along the x-axis, and change a and h. Every value in the readout is computed from the same model, and the dash pattern and the label on each curve say which is which, not only its colour.

Try it before reading on. Switch the curves on one at a time and drag the input xx along the axis, then press who wins? and watch how quickly exe^{x} leaves the plane on the right. Three of these curves, xx, x2x^{2} and exe^{x}, all climb; they do not climb in the same way. Switch on ln⁡x\ln x and drag xx to the left of zero: its row turns into a message, not a number. By the end of the chapter you will be able to say which curve is which from its shape, to read what two parameters do to any of them, and to say exactly where each stops being defined and where each stops being computable on a real machine.

Intuition: shape first

Most of the functions an engineer or a machine-learning practitioner meets are built from six simple shapes. Learn the shapes first; the formulas then explain them.

  • The line, y=xy=x. Steady change: each step right adds the same amount. Its graph is straight.
  • The parabola, y=x2y=x^{2}. Change that speeds up away from the bottom. It is symmetric: xx and −x-x give the same value, so squaring forgets signs.
  • The exponential, y=exy=e^{x}. Change in proportion to the amount already there. It is always positive, it never reaches the axis, and on the right it grows faster than any line or parabola, although not immediately.
  • The logarithm, y=ln⁡xy=\ln x. The exponential read backwards: it asks what power of ee gives xx? It exists only for x>0x>0, falls without bound as xx approaches 00, and climbs more and more slowly to the right.
  • The sine and the cosine, y=sin⁡xy=\sin x and y=cos⁡xy=\cos x. A wave that repeats every 2π2\pi and never leaves the band from −1-1 to 11. The cosine is the sine started a quarter of a period earlier.

Here e≈2.718282e\approx 2.718282 is the number for which the exponential has the pleasant property that its steepness at any point equals its height there. The book writes ≈\approx because ee is irrational and the digits are a rounding; the stage above uses the same rule, and it writes == only for values that are exactly known.

Definition

All six share one pattern. Take a basic function gg from the list and two numbers aa and hh:

y=a g(x−h),g∈{ x, x2, ex, ln⁡x, sin⁡x, cos⁡x }.y=a\,g(x-h),\qquad g\in\{\,x,\ x^{2},\ e^{x},\ \ln x,\ \sin x,\ \cos x\,\}.

The number aa is the vertical scale: it stretches the graph away from the xx-axis, and a negative aa also flips it upside down. The number hh is the horizontal shift: the graph of g(x−h)g(x-h) is the graph of gg moved right by hh, which is the opposite of what the minus sign tempts you to expect (the value gg had at 00 is now found at x=hx=h).

Every function here has a domain, the inputs for which it exists, and a range, the outputs it can produce. These come from gg and the shift, and they are the first thing to know:

  • xx and x2x^{2} and exe^{x} and sin⁡x\sin x and cos⁡x\cos x accept every real number; ln⁡x\ln x accepts only x>0x>0, so aln⁡(x−h)a\ln(x-h) exists only for x>hx>h, with a vertical asymptote at x=hx=h.
  • The range of asin⁡(x−h)a\sin(x-h) is the interval from −∣a∣-|a| to ∣a∣|a|. The range of a ex−ha\,e^{x-h} is the positive numbers when a>0a>0 and the negative numbers when a<0a<0. The range of aln⁡(x−h)a\ln(x-h) is every real number.
  • If a=0a=0 the result is the constant 00 (where it exists), whichever gg you chose. The stage flags that as a special case, because the shape disappears.

An exponential has a small surprise hidden in this pattern: shifting it and scaling it are the same operation, because a ex−h=(a e−h) exa\,e^{x-h}=(a\,e^{-h})\,e^{x}. Slide hh and watch the curve; then set aa close to e−he^{-h} (about 0.370.37 for h=1h=1) and the two curves become indistinguishable. Exactly equal needs a=e−ha=e^{-h}, an irrational number that the two-decimal field cannot hold. No other family does this.

Mechanics: shifts, scales and inverses

Shifts and scales

Use the stage at the top (or the full copy in the Explore section) to see the two parameters act. Set only ln⁡\ln on, then raise hh: the curve and its vertical asymptote move right together, and the thick bar on the xx-axis, where ln⁡\ln has no value, grows with them. Set only the sine on and raise aa to 33: the range becomes [−3,3][-3,3] and the zeros do not move, because a vertical stretch never moves the points where a function is 00. Raise hh instead and the zeros slide.

Inverse pairs and their honest domains

Two functions are inverses when each undoes the other. The exponential and the logarithm are one such pair, and squaring and the square root are another. On a graph, inverses are mirror images across the line y=xy=x, because undoing a function swaps the roles of input and output, and swapping coordinates is exactly that mirror.

The honest statement of the pair needs the domains:

ln⁡ ⁣(ex)=x  for every real x,eln⁡x=x  only for x>0.\ln\!\left(e^{x}\right)=x\ \text{ for every real }x,\qquad e^{\ln x}=x\ \text{ only for }x>0 .

The first holds everywhere because exe^{x} is defined and positive for every xx. The second needs x>0x>0 because ln⁡x\ln x does not exist otherwise. The square-and-root pair has the same trap in a different place: x2=∣x∣\sqrt{x^{2}}=|x|, which equals xx only when x≥0x\ge0, and (x)2=x\left(\sqrt{x}\right)^{2}=x only for x≥0x\ge0, since x\sqrt{x} does not exist for negative xx.

Undo it: a function and its inverse

Try these round trips

Coordinate plane from −5 to 5 on both axes with the exponential e to the x, the logarithm ln x, and the dashed line y = x: each graph is the mirror image of the other across that line. The point (1.5, 4.481689) lies on the graph of the first function and its mirror image (4.481689, 1.5) lies across the dashed line y = x.

input
1.5
step 1: eˣ (as a double)
4.481689
step 2: ln (as a double)
1.500000
distance from x
0

= exact (or the double the computer holds) · ≈ rounded to 6 decimals · ⚠ undefined

The point (1.5, 4.481689) and its mirror image (4.481689, 1.5) swap their coordinates.

ln(eˣ) = x for every real x. The identity holds at this x. The round trip returned x. ln undoes eˣ for every real x. The computer rounds eˣ once and ln once, so the result matches x to within a few units in the last place, which is all a double can promise.

ln⁡(ex)=xfor every real x\ln\left(e^{x}\right)=x\quad\text{for every real }x
ln⁡(ex)=ln⁡(e1.5)≈ln⁡(4.481689)≈1.5\begin{aligned}\ln\left(e^{x}\right)&=\ln\left(e^{1.5}\right)\\&\approx \ln\left(4.481689\right)\\&\approx 1.5\end{aligned}
Pair
Order

from −800 to 800, up to 2 decimal places

Choose a pair and an order, then drag x or type it. The dashed line is y = x; a point and its mirror image swap coordinates, and the open ring marks a point that comes back somewhere other than where it started.

Try the presets in turn. ln⁡(e1.5)\ln(e^{1.5}) comes back, and so does ln⁡(e−3)\ln(e^{-3}): negative inputs are fine for the exponential. eln⁡(−2)e^{\ln(-2)} cannot even start, because the first step has no value. (−2)2\sqrt{(-2)^{2}} comes back as 22, not −2-2: the square forgot the sign, and the stage shows where the lost point lands on the other branch of the parabola. And the two overflow presets show that a round trip that is mathematically perfect can still fail on a computer; the row says so, labelled “as a double”.

The unit circle

Trigonometry begins with one circle. The unit circle is the circle of radius 11 centred at the origin. Start at (1,0)(1,0) and walk counter-clockwise a distance θ\theta along the circle; the point you reach is, by definition,

(cos⁡θ, sin⁡θ).(\cos\theta,\ \sin\theta).

The distance walked, θ\theta, is measured in radians: one full turn is 2π2\pi because the circumference of a circle of radius 11 is 2π2\pi. So π\pi is a half-turn, π/2\pi/2 a quarter-turn, and 180∘=π180^{\circ}=\pi radians. Walking clockwise is a negative angle, matching the convention used for vector directions in the vectors chapter. Walking a whole turn more brings you back to the same point, which is why both functions repeat: sin⁡(θ+2π)=sin⁡θ\sin(\theta+2\pi)=\sin\theta.

Because the point lies on the circle, its coordinates satisfy cos⁡2θ+sin⁡2θ=1\cos^{2}\theta+\sin^{2}\theta=1: it is Pythagoras applied to the right triangle with the radius as hypotenuse.

Walk around the unit circle

Jump to an exact angle

The unit circle in a plane from −1.6 to 1.6 on both axes. The point at angle π/6 radians is in quadrant I. Its x-coordinate is cosine and equals exactly square root of 3 over 2, approximately 0.866; its y-coordinate is sine and equals exactly one half, approximately 0.500. A coloured horizontal segment shows the cosine and a vertical segment shows the sine.

angle
π/6 rad0.523599 rad…
the same angle in degrees
30°
cosine: the x-coordinate
√3/20.866025…
sine: the y-coordinate
1/20.500000
sum of the squares
1
sine one full turn later
1/20.500000
arcsin of the sine
π/6 rad0.523599 rad…
atan2 of the coordinates
π/6 rad0.523599 rad…

= exact · ≈ rounded to 6 decimals

The graphs of sine and cosine from −2π to 2π radians. A vertical line marks the angle θ = π/6; the sine graph is at height exactly one half, approximately 0.500 and the cosine graph at height exactly square root of 3 over 2, approximately 0.866.

The graphs use different scales on the two axes (θ across, height up), unlike the circle above, which has the same scale in both directions.

The point is in quadrant I: cos θ > 0 and sin θ > 0. Its reference angle (the acute angle to the x-axis) is π/6. arcsin(sin θ) = θ here, because θ lies between −π/2 and π/2. atan2(sin θ, cos θ) = θ here, because θ lies in (−π, π].

θ=π6 rad=30∘cos⁡θ=32sin⁡θ=12\begin{aligned}\theta&=\frac{\pi}{6}\ \mathrm{rad}=30^{\circ}\\\cos\theta&=\frac{\sqrt{3}}{2}\\\sin\theta&=\frac{1}{2}\end{aligned}
cos⁡2θ+sin⁡2θ=34+14=1\begin{aligned}\cos^{2}\theta+\sin^{2}\theta&=\frac{3}{4}+\frac{1}{4}\\&=1\end{aligned}
arcsin⁡(sin⁡θ)=π6=θatan2⁡(sin⁡θ,cos⁡θ)=π6=θ\begin{aligned}\arcsin(\sin\theta)&=\frac{\pi}{6}=\theta\\\atantwo(\sin\theta,\cos\theta)&=\frac{\pi}{6}=\theta\end{aligned}
Angles

from −24 to 24, whole numbers only

Drag the point round the circle, use the arrow keys on it (Shift for bigger steps), or type an angle. The horizontal leg is cos θ, the vertical leg is sin θ, and the two graphs below show the same two numbers as θ varies.

Some angles have exact coordinates built from 2\sqrt2, 3\sqrt3 and small fractions. The stage in its exact mode snaps to multiples of π/12\pi/12 and shows them with ==. The table lists the first half-turn, straight from the model:

angle θdegreescos θ (exact)sin θ (exact)cos θ ≈sin θ ≈
00°101.0000000.000000
π/1215°(√6+√2)/4(√6−√2)/40.9659260.258819
π/630°√3/21/20.8660250.500000
π/445°√2/2√2/20.7071070.707107
π/360°1/2√3/20.5000000.866025
5π/1275°(√6−√2)/4(√6+√2)/40.2588190.965926
π/290°010.0000001.000000
7π/12105°−(√6−√2)/4(√6+√2)/4−0.2588190.965926
2π/3120°−1/2√3/2−0.5000000.866025
3π/4135°−√2/2√2/2−0.7071070.707107
5π/6150°−√3/21/2−0.8660250.500000
11π/12165°−(√6+√2)/4(√6−√2)/4−0.9659260.258819
π180°−10−1.0000000.000000

The other quadrants follow from the first by reflection. Take the reference angle, the acute angle between the radius and the xx-axis, read its unsigned values from the table, and put the signs back from the quadrant: in quadrant II cosine is negative and sine positive, in quadrant III both are negative, in quadrant IV cosine is positive and sine negative.

Two inverse functions go with the circle, and both have limited ranges. arcsin⁡\arcsin returns only angles from −π/2-\pi/2 to π/2\pi/2, so arcsin⁡(sin⁡θ)=θ\arcsin(\sin\theta)=\theta only for those θ\theta; for θ=2\theta=2 it returns π−2\pi-2, the other angle with the same sine. The two-argument function atan2⁡(y,x)\operatorname{atan2}(y,x), met in the vectors chapter, returns the angle in (−π,π](-\pi,\pi] from both coordinates, so it recovers θ\theta up to whole turns. The verdict line under the stage says, for each angle, whether arcsin⁡\arcsin and atan2⁡\operatorname{atan2} give the angle back.

Changing the base

The exponential exe^{x} is one member of a family. For any base b>0b>0 with b≠1b\ne1 we have bx=exln⁡bb^{x}=e^{x\ln b}, so every exponential is the natural one with the input rescaled by the constant ln⁡b\ln b. The inverse of bxb^{x} is the logarithm to the base bb, written log⁡bx\log_{b}x: the power of bb that gives xx. It exists for x>0x>0 only.

Base 11 is excluded because 1x=11^{x}=1 for every xx: it is a constant, not an exponential, and its “logarithm” would have to answer what power of 11 gives 77? — nothing does. For a base between 00 and 11 the curve falls instead of rising (halving rather than doubling).

Any logarithm is a natural logarithm divided by a constant, which is how a computer evaluates all of them:

log⁡bx=ln⁡xln⁡b(x>0, b>0, b≠1).\log_{b}x=\frac{\ln x}{\ln b}\qquad(x>0,\ b>0,\ b\ne1).

The same constant gives the doubling time. For b>1b>1 the quantity bxb^{x} doubles every time xx grows by ln⁡2/ln⁡b\ln 2/\ln b, and for 0<b<10<b<1 it halves every ln⁡2/∣ln⁡b∣\ln 2/|\ln b|. And it converts units of information: log⁡2x=ln⁡x/ln⁡2\log_{2}x=\ln x/\ln 2 counts bits and ln⁡x\ln x counts nats.

Finally, these identities hold for positive numbers and are what make logarithms useful (the last is the special case b=2b=2 of the third, which is how bits are computed):

ln⁡(ab)=ln⁡a+ln⁡b,ln⁡ ⁣(ak)=kln⁡a,log⁡ba=ln⁡aln⁡b,log⁡2a=ln⁡aln⁡2.\ln(ab)=\ln a+\ln b,\qquad \ln\!\left(a^{k}\right)=k\ln a,\qquad \log_{b}a=\frac{\ln a}{\ln b},\qquad \log_{2}a=\frac{\ln a}{\ln 2} .

Change the base, check the identities

Try these

Coordinate plane from −4 to 8 on both axes with the graphs of b to the x and the logarithm of x to the base b for b = 2, and the dashed line y = x: the two graphs are mirror images across it. At x = 2 the power is exactly 4 and the logarithm is exactly 1.

base
2
the power b to the x
4
logarithm of x to the base b
1
natural logarithm of the base
0.693147
time to double
1
x in bits: log base 2
1
x in nats: natural log
0.693147

= exact · ≈ rounded to 6 decimals · ⚠ undefined

b > 1: b^x grows, and doubles every 1 unit of x.

bx=22=4\begin{aligned}b^{x}&=2^{2}\\&=4\end{aligned}
log⁡bx=ln⁡xln⁡b=ln⁡(2)ln⁡(2)≈0.6931470.693147=1\begin{aligned}\log_b x&=\dfrac{\ln x}{\ln b}=\dfrac{\ln(2)}{\ln(2)}\\&\approx\dfrac{0.693147}{0.693147}\\&=1\end{aligned}
Base

from −4 to 8, up to 2 decimal places

Four identities, checked on a computer

Each identity is exact in mathematics. The computer rounds every step, so each card shows both sides, their difference and the tolerance it is judged against.

from −10 to 1000, up to 2 decimal places

from −10 to 1000, up to 2 decimal places

from −20 to 20, up to 2 decimal places

  • ln⁡(ab)=ln⁡a+ln⁡b\ln(ab)=\ln a+\ln b
    left side, ln(ab)
    ≈ 3.178054
    right side, ln a + ln b
    ≈ 3.178054
    difference, left − right
    ≈ 4.44×10⁻¹⁶
    tolerance (a few units in the last place)
    ≤ 5.65×10⁻¹⁵

    ✓ within tolerance: the two sides agree as far as a double can tell

  • ln⁡(ak)=kln⁡a\ln(a^{k})=k\ln a
    left side, ln(aᵏ)
    ≈ 5.375278
    right side, k · ln a
    ≈ 5.375278
    difference, left − right
    ≈ 0
    tolerance (a few units in the last place)
    ≤ 9.55×10⁻¹⁵

    ✓ within tolerance: the two sides agree as far as a double can tell

  • log⁡ba=ln⁡aln⁡b\log_b a=\dfrac{\ln a}{\ln b}
    left side, a
    ≈ 6
    right side, b^(ln a / ln b)
    ≈ 6
    difference, left − right
    ≈ 0
    tolerance (a few units in the last place)
    ≤ 2.98×10⁻¹⁴

    ✓ within tolerance: the two sides agree as far as a double can tell

  • log⁡2a=ln⁡aln⁡2\log_2 a=\dfrac{\ln a}{\ln 2}
    left side, log₂ a
    ≈ 2.584963
    right side, ln a / ln 2
    ≈ 2.584963
    difference, left − right
    ≈ 0
    tolerance (a few units in the last place)
    ≤ 4.59×10⁻¹⁵

    ✓ within tolerance: the two sides agree as far as a double can tell

Choose a base and an input to see b to the x and its logarithm as mirror images. Below, the identity checker evaluates both sides of each identity on a computer and shows the difference and the tolerance it is judged against.

Exact mathematics says both sides of each identity are equal. The computer rounds every step, so the two sides can differ in the last digits; the stage shows that difference and a tolerance of a few units in the last place. The checker also shows when an identity cannot be checked at all: if aa is not positive, ln⁡a\ln a does not exist and the card says so, rather than inventing a number.

Worked examples

Four computations, each shown step by step with every number taken from the same model as the stages. Step forward and back with the buttons; going back selects an earlier step, and nothing is undone.

Worked examples, step by step

Choose an example

y=aln⁡(x−h)=2ln⁡(x−1)y=a\ln(x-h)=2\ln(x-1)

Read the parameters. The vertical scale is a = 2 and the graph is shifted to the right by h = 1. We want the value at x = 5.

Choose an example and step through the work. The first is a shifted and scaled logarithm, the second a round trip, the third a point on the unit circle, and the last a change of base.

Executable reference code

Run the Python examples below to follow the calculations step by step. The comments record what each line returns.

First the exponential and the logarithm: the round trip, the places where each fails, a square and its root, change of base, and bits and nats. Notice the line math.log(1000, 10): it returns 2.9999999999999996, because it divides two rounded logarithms, while math.log10(1000.0) is built for the job and returns 3.0.

code/python/families_exp_log.pyexp, ln and their limits
import math

# ln undoes e^x for EVERY real x: ln(e^x) = x. The computer rounds twice, so the answer can differ in the last digits.
x = 1.5
back = math.log(math.exp(x))  # 1.5 (here it happens to come back exactly)

# e^x is larger than the largest double (about 1.8e308) once x > 709.78. Python raises an error; NumPy would return inf.
try:
    math.exp(710.0)
except OverflowError:
    overflow = "OverflowError"

# ln x does not exist for x <= 0: no power of e is zero or negative.
try:
    math.log(0.0)
except ValueError:
    no_log_of_zero = "ValueError"

# e^(ln x) = x only for x > 0. At x = 10 the round trip is a hair off, because ln 10 is stored rounded.
exp_of_ln = math.exp(math.log(10.0))  # 10.000000000000002: compare with math.isclose, never ==
exp_of_ln_close = math.isclose(exp_of_ln, 10.0, rel_tol=1e-12)  # True

# Square then root: sqrt(x**2) is |x|, not x. The sign is lost on the way up.
sqrt_of_square = math.sqrt((-3.0) ** 2)  # 3.0

# Change of base: log_b a = ln a / ln b. In floating point the quotient is not always the integer you expect.
log2_of_8 = math.log2(8.0)  # 3.0, exactly (math.log2 is built for powers of two)
log_1000_base_10 = math.log(1000, 10)  # 2.9999999999999996 (a quotient of two rounded logarithms)
log10_of_1000 = math.log10(1000.0)  # 3.0 (the dedicated function)

# Bits and nats: log2(a) = ln(a) / ln(2).
bits = math.log(1024.0) / math.log(2.0)  # 10.0
nats = math.log(1024.0)  # 6.931471805599453

# A doubling time: how far must x go for 3**x to double?  log_3(2) = ln 2 / ln 3.
doubling_time = math.log(2.0) / math.log(3.0)  # 0.6309297535714574

print(back, overflow, no_log_of_zero, exp_of_ln, exp_of_ln_close, sqrt_of_square, log2_of_8, log_1000_base_10, log10_of_1000, bits, nats, doubling_time)

Then trigonometry. All Python trigonometric functions take radians. The file shows that sin⁡π\sin\pi is not zero (it is about 1.2×10−161.2\times10^{-16}), why you compare with a tolerance, and the two behaviours from the unit circle: arcsin⁡(sin⁡2)\arcsin(\sin 2) is not 22, and atan2 returns the angle modulo a turn.

code/python/families_trig.pyradians, periodicity, arcsin versus atan2
import math

# Python's trigonometric functions take RADIANS. A full turn is 2*pi.
theta = math.pi / 6
cos_t, sin_t = math.cos(theta), math.sin(theta)  # 0.8660254037844387 and 0.49999999999999994: sqrt(3)/2 and 1/2 up to rounding

# cos^2 + sin^2 = 1 holds exactly in mathematics; the doubles agree to about 1e-16, so compare with isclose.
pythagorean_gap = cos_t**2 + sin_t**2 - 1.0
pythagorean_ok = math.isclose(cos_t**2 + sin_t**2, 1.0, rel_tol=1e-15)

# pi is stored rounded, so sin(pi) is not 0 and cos(pi/2) is not 0. Never test a trigonometric value with ==.
sin_pi = math.sin(math.pi)  # 1.2246467991473532e-16
cos_half_pi = math.cos(math.pi / 2)  # 6.123233995736766e-17
sin_pi_is_zero = math.isclose(sin_pi, 0.0, abs_tol=1e-12)  # True: ask for a tolerance

# Periodicity: adding a full turn gives the same point (to rounding).
periodic = math.isclose(math.sin(theta + 2 * math.pi), math.sin(theta), rel_tol=0, abs_tol=1e-15)

# arcsin(sin t) is NOT t unless t is in [-pi/2, pi/2]: arcsin only returns angles in that interval.
arcsin_of_sin_2 = math.asin(math.sin(2.0))  # 1.1415926535897933, which is pi - 2 up to rounding

# atan2(sin t, cos t) IS t modulo 2*pi, in (-pi, pi]: it sees the signs of both components.
atan2_of_4 = math.atan2(math.sin(4.0), math.cos(4.0))  # -2.2831853071795867, which is 4 - 2*pi up to rounding

# Degrees and radians: 180 degrees is pi radians.
thirty_degrees = math.radians(30.0)  # 0.5235987755982988
back_to_degrees = math.degrees(math.pi / 6)  # 29.999999999999996: close to 30, not equal

print(cos_t, sin_t, pythagorean_ok, sin_pi, cos_half_pi, sin_pi_is_zero, periodic, arcsin_of_sin_2, atan2_of_4, thirty_degrees, back_to_degrees)

Finally the practical form of the exponential in machine learning: the softmax, which overflows if written naively, and the standard shift that fixes it.

code/python/families_stable_exp_numpy.pyoverflow and the stable softmax
import numpy as np

# Scores ("logits") from a model. Softmax turns them into probabilities: exp(s_i) / sum_j exp(s_j).
logits = np.array([1000.0, 1001.0, 1002.0])

# e^1000 is far above the largest double (about 1.8e308), so NumPy returns inf, and inf / inf is nan.
with np.errstate(over="ignore", invalid="ignore"):
    naive = np.exp(logits) / np.exp(logits).sum()  # [nan nan nan]

# The probabilities do not change if every score is shifted by the same amount: e^(s - m) / sum e^(s_j - m) = e^s / sum e^(s_j).
# Shift by the largest score m, so the largest exponent is e^0 = 1 and nothing can overflow.
shifted = np.exp(logits - logits.max())
stable = shifted / shifted.sum()  # [0.09003057 0.24472847 0.66524096]

# The same idea for log(sum(exp(s))): m + log(sum(exp(s - m))).
log_sum_exp = logits.max() + np.log(shifted.sum())  # 1002.4076059644444

print(naive, stable, log_sum_exp)

Explore: change the parameters

This is the whole comparison on one plane, with the facts about each visible curve in cards underneath: domain, range, zeros, asymptote, behaviour and symmetry. These questions have definite answers; check them against the stage.

Slide, stretch and compare

Draw these functions

Or start from

Coordinate plane from −7 to 7 on both axes. Vertical scale a is 1 and horizontal shift h is 0. The drawn curves are y equals a times g of x minus h for e to the x, natural log of x, sine of x. A vertical dashed line marks the input x = 1. Values at that input: e to the x: approximately 2.718; natural log of x: exactly 0; sine of x: approximately 0.841.

input
1
shifted input x − h
1
a·e^(x − h)
2.718282
a·ln(x − h)
0
a·sin(x − h)
0.841471

= exact · ≈ rounded to 6 decimals · ⚠ undefined

At x = 1 the highest curve is eˣ (2.718282) and the lowest is ln x (0).

y=a ex−h=1⋅e1−0=1⋅e1≈2.718282\begin{aligned}y&=a\,e^{x-h}\\&=1\cdot e^{1-0}\\&=1\cdot e^{1}\\&\approx 2.718282\end{aligned}
y=a ln⁡(x−h)=1⋅ln⁡(1−0)=1⋅ln⁡(1)=0\begin{aligned}y&=a\,\ln(x-h)\\&=1\cdot \ln(1-0)\\&=1\cdot \ln(1)\\&=0\end{aligned}
y=a sin⁡(x−h)=1⋅sin⁡(1−0)=1⋅sin⁡(1)≈0.841471\begin{aligned}y&=a\,\sin(x-h)\\&=1\cdot \sin(1-0)\\&=1\cdot \sin(1)\\&\approx 0.841471\end{aligned}

a·e^(x − h)

Domain
all real numbers
Range
(0, ∞)
Zeros
none
Asymptote
the x-axis (y = 0), approached as x goes to −∞
Behaviour
increasing everywhere, faster and faster
Symmetry
none

a·ln(x − h)

Domain
x > 0
Range
all real numbers
Zeros
x = 1
Asymptote
the vertical line x = 0
Behaviour
increasing, but ever more slowly
Symmetry
none

a·sin(x − h)

Domain
all real numbers
Range
[−1, 1]
Zeros
x = kπ for every integer k
Asymptote
none
Behaviour
oscillates between −1 and 1, repeating every 2π
Symmetry
turned half a turn about the point (0, 0)

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −6 to 6, up to 2 decimal places

The full comparison. Turn families on, change a and h, and read the facts for every visible curve. The thick bar on the x-axis marks where the logarithm has no value.
  • Switch on xx, x2x^{2} and exe^{x} together with a=1a=1 and h=0h=0. Where do the line and the parabola cross? Does exe^{x} ever fall below x2x^{2}? (For positive xx it never does: the smallest ratio ex/x2e^{x}/x^{2} is e2/4≈1.85e^{2}/4\approx1.85, at x=2x=2. For negative xx it does, until they cross near x≈−0.70x\approx-0.70.) The exercise below asks the same question for 2x2^{x}, where the answer is different.
  • Turn ln⁡\ln on and raise hh to 33. Where is its zero, and where is its asymptote? Why is the zero not at the asymptote?
  • Set a=−1a=-1 on the parabola. What happens to its range, and to the facts card?
  • Turn on the sine and cosine with a=1a=1. Which value of hh for the sine brings it closest to the cosine? (Think of a quarter of a period, and of the direction a positive hh moves a graph. The exact answer is −π/2≈−1.571-\pi/2\approx-1.571; the arrows and the buttons step by 0.50.5, so they reach −1.5-1.5; typing a value allows two decimals.)
  • Make a=0a=0. What do all the families have in common?

Common mistakes

Numerical considerations

The exponential has a narrow window in which a double can hold it. The largest double is about 1.8×103081.8\times10^{308}, so exe^{x} overflows just above x=709.78x=709.78; the smallest positive double is about 5×10−3245\times10^{-324}, so exe^{x} underflows to exactly 00 just below x=−745.13x=-745.13. The table is computed by the same model as the stages above.

xeˣ as a doublewhat happened
1≈ 2.718282a finite double
10≈ 22026.465795a finite double
100≈ 2.68812×10⁴³a finite double
700≈ 1.01423×10³⁰⁴a finite double
709≈ 8.21841×10³⁰⁷a finite double
710= ∞overflow: the true value is too large for a double
−700≈ 9.85968×10⁻³⁰⁵a finite double
−745≈ 4.94066×10⁻³²⁴a finite double
−746= 0underflow: the true value is too small for a double
−800= 0underflow: the true value is too small for a double

When the stored value is ∞\infty or 00, the stage writes == because it is stating a fact about the double (“the stored value is ∞\infty”), and it adds a note giving the truth: the real value is finite and large, or positive and tiny. Python and NumPy even disagree on what to do. math.exp(710.0) raises OverflowError; np.exp(710.0) quietly returns inf, and inf / inf is nan, which then poisons every number it touches.

Three more places where the machine and the mathematics part ways. First, eln⁡xe^{\ln x} is xx only up to rounding: math.exp(math.log(10.0)) is 10.000000000000002. Second, π\pi is stored rounded, so sin⁡π\sin\pi is about 1.2×10−161.2\times10^{-16}, not 00, and cos⁡(π/2)\cos(\pi/2) is about 6×10−176\times10^{-17}. Third, math.log(1000, 10) is 2.9999999999999996 but math.log10(1000.0) is 3.0: when a dedicated function for your base exists, use it.

Connections to engineering and machine learning

  • Softmax and log-sum-exp. A classifier turns scores sis_i into probabilities esi/∑jesje^{s_i}/\sum_j e^{s_j}. With scores near 10001000 the exponentials overflow. Subtracting the largest score mm multiplies the top and the bottom by the same number e−me^{-m}, so the probabilities do not change, and every exponent becomes at most 00. The same shift gives ln⁡∑jesj=m+ln⁡∑jesj−m\ln\sum_j e^{s_j}=m+\ln\sum_j e^{s_j-m}, the standard stable form used in the loss functions of almost every framework.
  • Logarithms turn products into sums. The likelihood of 10001000 independent events each with probability 0.010.01 is 10−200010^{-2000}, which underflows to 00 in a double. The log-likelihood is 1000ln⁡0.01≈−4605.171000\ln 0.01\approx-4605.17, an ordinary number. This is why models are trained on the log-likelihood.
  • Bits and nats. Cross-entropy and information are measured in nats when computed with ln⁡\ln (the default in most libraries) and in bits with log⁡2\log_2; one nat is 1/ln⁡2≈1.44271/\ln2\approx1.4427 bits. Telling 10241024 equally likely cases apart takes log⁡21024=10\log_21024=10 bits.
  • Exponential growth and decay. Compound growth, radioactive decay, learning-rate schedules and the attenuation of a signal are all a bxa\,b^{x}; the doubling or halving time ln⁡2/∣ln⁡b∣\ln2/|\ln b| is the one number that describes them.
  • Sine and cosine. Every periodic signal is built from them, and a rotation of the plane by θ\theta is the matrix whose entries are cos⁡θ\cos\theta and sin⁡θ\sin\theta. Positional encodings in transformers use sines and cosines of many frequencies; all of them take radians.
  • The logarithm as a compressor. On a log axis, multiplying a quantity by a fixed factor moves it a fixed distance. This is why spectra, learning curves and file sizes are plotted that way.

Exercises

Answer each question and press Check. A wrong answer tells you which mistake it looks like. After one attempt you may open a worked solution.

prediction

When does 2ˣ overtake x²?

Compare 2ᵏ and k² for the whole numbers k = 1, 2, 3, 4, 5, … What is the smallest whole number n such that 2ᵏ is strictly larger than k² for EVERY whole number k ≥ n?

explanation

Which round trip always works?

Inverse functions undo each other, but only on the right domain. Which of these statements is true for EVERY real number x it makes sense to ask about?

Choose one answer

calculation

Square, then root

Start with x = −7. Square it, then take the (principal, non-negative) square root of the result. What number do you end with?

calculation

A cosine from the unit circle

Use the unit circle to find cos(5π/6) as a decimal rounded to 3 places. (The angle is in radians, and 5π/6 is 150°.)

prediction

Does arcsin undo sin?

Take the angle θ = 2 radians (about 114.6°). Predict the value of asin(sin 2) to 4 decimal places.

prediction

How many angles have this sine?

How many angles θ in the half-open interval [0, 2π) satisfy sin θ = 1/2?

calculation

Bits needed

A system must tell 1024 equally likely cases apart. How many bits does that take? (A bit is one answer to a yes/no question, and the number of bits is log₂ of the number of cases.)

prediction

What does the computer do with e⁷¹⁰?

The largest double is about 1.8 × 10³⁰⁸, and e⁷¹⁰ is just larger than that. In Python, what does math.exp(710.0) do? (NumPy's np.exp(710.0) behaves differently from the math module.)

Choose one answer

explanation

Why subtract the maximum?

Softmax computes eˢⁱ / (eˢ¹ + eˢ² + …). With scores like 1000, 1001, 1002 the exponentials overflow. The stable version computes e^(sᵢ − m) / (e^(s₁ − m) + …) with m the largest score. Why is that the same answer?

Choose one answer

construction

Read the shift off a logarithm

The graph of y = 2·ln(x − h) crosses the x-axis at x = 5. What is h?

Summary and checkpoints

  • Six shapes carry most of the work: the line, the parabola, the exponential, the logarithm, the sine and the cosine. Each is a g(x−h)a\,g(x-h) for a basic gg: aa stretches vertically, hh shifts right.
  • Domains matter. ln⁡\ln exists only for positive inputs; \sqrt{} only for non-negative ones. ln⁡(ex)=x\ln(e^{x})=x for every xx, but eln⁡x=xe^{\ln x}=x only for x>0x>0, and x2=∣x∣\sqrt{x^{2}}=|x|.
  • Inverse functions are mirror images across y=xy=x.
  • On the unit circle, (cos⁡θ,sin⁡θ)(\cos\theta,\sin\theta) is the point at distance θ\theta (radians) from (1,0)(1,0), and cos⁡2θ+sin⁡2θ=1\cos^{2}\theta+\sin^{2}\theta=1. arcsin⁡\arcsin returns only angles in [−π/2,π/2][-\pi/2,\pi/2]; atan2⁡\operatorname{atan2} returns angles in (−π,π](-\pi,\pi].
  • log⁡bx=ln⁡x/ln⁡b\log_{b}x=\ln x/\ln b; the doubling time is ln⁡2/ln⁡b\ln2/\ln b; bits use base 22, nats use base ee.
  • In code: radians everywhere, tolerances instead of ==, shift exponents before using them, and expect exp to overflow near 709.78709.78.

Checkpoints. You are ready to move on when you can, without looking:

  1. Sketch ln⁡(x−2)\ln(x-2) and name its domain, its asymptote and its zero.
  2. Say why x2\sqrt{x^{2}} is not always xx, and for which xx it is.
  3. Give cos⁡\cos and sin⁡\sin of 7π/67\pi/6, with signs, and say which quadrant that is.
  4. Explain why arcsin⁡(sin⁡2)≠2\arcsin(\sin 2)\ne2, and what it equals.
  5. Compute log⁡21024\log_{2}1024 and explain how it differs from ln⁡1024\ln1024.
  6. Say what happens to e710e^{710} in Python and in NumPy, and how to avoid the overflow in a softmax.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available