Anything that repeats, a sound, a season, a heartbeat, can be described as a wave. A sine wave is simply the height of the turning arm from the last lesson, drawn out over time. Three numbers set its shape: how tall, how fast and how far shifted. In AI, sound reaches a model as a long list of wave samples, and transformers use waves of different speeds to tell the first word of a sentence from the fiftieth. This lesson reads the three dials off a formula, samples a wave into a list the way a microphone does, and builds the position codes a transformer uses.
What you'll be able to do
Read a sine wave as the height of a turning arm over time
Name a wave's amplitude, period and phase shift, and read them from y = A sin(kx + φ)
Sample a wave into a list in Python, and see what too few samples lose
See sound as a list of samples, and how a transformer tells positions apart with waves
Quick check
Have a guess before you start. An arm turns round and round. If you plot its height over time, what shape do you get?
A wave that rises and falls forever
A circle drawn round and round
A single bump that then stays flat
A straight line rising steadily upward
Show the answer
A wave that rises and falls forever
The height goes up to the top, down through the middle to the bottom, and back, every turn: a repeating wave. That wave is the sine wave.
The math: a turning arm, drawn over time
Purpose. Describe anything that repeats.
In the last lesson, an arm of length 1 at angle x had height sin x. Let the angle grow steadily, like time passing, and plot the height: it rises from 0 to 1 at a quarter turn, falls back to 0 at a half turn, down to −1 at three quarters, and back to 0 after a full turn. Then it all repeats. That's the sine wave.
Three numbers stretch and slide it into any wave you need:
y=Asin(kx+φ)
In plain words: A sets how tall, k how fast it repeats, and φ (phi) how far it's slid along.
Quick check
From the last lesson: what is sin 90°?
0.5
0
−1
1
Show the answer
1
At 90° the arm points straight up, so its height is 1, the top of the wave.
Sampling. A computer can't store a smooth curve, so it stores the wave's height at evenly spaced points: samples. Watch a wave with amplitude 2 sampled 8 times across one full cycle. In the picture, an arm 2 long turns an eighth of a turn each step, and its tip's height becomes the next point of the wave beside it. Straight lines join the points, because the samples are all the computer keeps.
Try it now
Then set the samples to 2 and press Use these numbers: both samples land on 0, and the joined wave in the picture is flat. Try 4, then 16.
Symbols and formula. The three dials:
amplitude=Aperiod=k2πshift=φ
In plain words: the amplitude is the height of a peak. The period is how long one full cycle takes: a bigger k packs the cycles closer. The phase shift slides the wave along without changing its shape.
The three pictures below each turn one dial. Each starts from y = sin x, drawn dashed, and draws the new wave thick on top, so you can see exactly what that one number changed.
So y = 3 sin(2x) has peaks of 3 and repeats every 2π/2 = π, twice as often as plain sin x. Shifting sin x by φ = π/2 makes it start at its peak instead of at 0: that's exactly cos x, the same wave a quarter turn ahead.
Reading a wave from its formula. Take y = 0.5 sin(4x). The number in front, 0.5, is the amplitude, so the wave swings between −0.5 and 0.5. The number multiplying x, 4, is the speed, so the period is 2π/4 = π/2 ≈ 1.57, and four cycles fit where sin x makes one. There's nothing added inside the brackets, so there's no shift: the wave starts at 0 and rises. Reading all three dials first tells you what to expect before you plot a single point, and a plot that disagrees points straight at the slip. A minus sign in front, as in −2 sin x, flips the wave upside down: it starts at 0 and falls first, with peaks still 2 high.
Quick check
What is the period of y = sin(3x)?
2π/3, about 2.09
3
π/3
3 × 2π
Show the answer
2π/3, about 2.09
The period is 2π/k = 2π/3. A bigger k means a shorter period: three cycles fit where one used to.
Quick check
Which wave has the tallest peaks: 4 sin(x), sin(4x) or sin(x + 4)?
4 sin(x)
sin(4x)
sin(x + 4)
All three peak at 4
Show the answer
4 sin(x)
Only 4 sin(x) multiplies the height: its peaks are 4. sin(4x) repeats faster and sin(x + 4) is shifted, but both still peak at 1.
In your own words
In your own words: what do A, k and φ each change about a wave?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: a wave as a list of samples
Purpose. Turn a wave into numbers a program can store and use.
import math
samples = []
for i inrange(8):
x = i * 2 * math.pi / 8
samples.append(round(math.sin(x), 3))
print(samples)
It runs right here in your browser, with nothing to install.
Each x is one eighth of a cycle further on, and each sample is the wave's height there. The list rises to 1, falls through 0 to −1, and comes back. Change the 8 to sample more or fewer points per cycle.
Code flow. Here is the flow's wave, y = 2 sin x, sampled by the same loop. Step through it and watch x move on an eighth of a cycle each time round, and samples grow by one box: the eight numbers the flow wrote, rounded to 3 places.
Too few samples lose the wave. Sample the same wave with fewer and fewer points per cycle:
import math
for n in [2, 4, 8]:
samples = []
for i inrange(n):
samples.append(round(math.sin(i * 2 * math.pi / n), 3))
print(n, samples)
With 8 samples the shape is clear. With 4 it's a rough zig-zag. With 2 both samples land where the wave crosses 0, and the wave vanishes entirely. A rule of thumb: you need more than 2 samples per cycle of the fastest wave you want to keep. That's why audio is recorded tens of thousands of times a second.
Draw it. With plenty of samples, the joined points look like the smooth wave. Given one list, plt.plot puts each sample at its place in the list: sample 0, sample 1, and so on along the bottom. This cell takes 41 samples of y = 2 sin x, 40 even steps across one cycle, so sample 40 lands where the next cycle starts:
import math
import matplotlib.pyplot as plt
ys = []
for i inrange(41):
ys.append(2 * math.sin(i * 2 * math.pi / 40))
plt.plot(ys)
plt.xlabel("sample number i")
plt.ylabel("y = 2 sin x")
plt.show()
Quick check
Read the plot. At which sample number does the wave reach its lowest point, −2?
40
30
20
10
Show the answer
30
The lowest point comes three quarters of the way through a cycle, and three quarters of 40 steps is 30. Sample 10, a quarter of the way, is the peak, 2.
Worked example
Worked example: two waves added
Add a slow wave and a fast wave at a few points, the way sounds mix.
import math
total = []
for i inrange(8):
x = i * 2 * math.pi / 8
slow = math.sin(x)
fast = 0.5 * math.sin(3 * x)
total.append(round(slow + fast, 3))
print(total)
In the lesson you can change this and run it.
The slow wave completes one cycle across the 8 points; the fast one, with k = 3, completes three, at half the height. Adding them sample by sample gives a new list: the slow rise and fall, with a ripple riding on it. Sound works exactly like this: two notes played together are two waves added, and a recording stores only the sum.
3 × sin(π/2) = 3 × 1 = 3.0, the peak. Shifting by another π/2 reaches π, where the wave is back at 0.
Quick check
Which line computes 8 samples across one cycle of sin x?
i / 8 for i from 0 to 7
i * 8 for i from 0 to 7
i * 2 * math.pi / 8 for i from 0 to 7
i * math.pi for i from 0 to 7
Show the answer
i * 2 * math.pi / 8 for i from 0 to 7
One cycle is 2π long, so 8 even steps are 2π/8 apart: i × 2π/8.
Drill
Sample a wave
Fix the loop so wave holds 12 samples of y = 2 sin(x) across one cycle, rounded to 3 places.
import math
wave = []
for i inrange(12):
x = i * 2 * math.pi / 8
wave.append(round(math.sin(x), 3))
print(wave)
In the lesson, your code is checked as you write it.
In your own words
Why did sampling sin x at 2 points per cycle make the wave vanish?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: sounds and positions
Purpose. Waves reach models in two ways.
Sound is a list of samples. A microphone measures air pressure thousands of times a second, and a speech model receives exactly that: a long list of wave heights, like the lists above. This lesson's sampling rule is why speech is usually recorded at 16,000 samples a second or more.
Positions as waves. A transformer reads all the words of a sentence at once, so it needs another way to know their order. The original transformer gave position p a list of wave values at several speeds:
code(p)=(sins1p,coss1p,sins2p,coss2p,…)
In plain words: each position gets the heights of several waves, some fast and some slow. Fast waves tell neighbors apart; slow waves tell the start from the end.
Quick check
What does this print?
import math
p = 1print(round(math.sin(p / 1), 3), round(math.sin(p / 10), 3))
0.1 0.841
0.841 0.841
1.0 0.1
0.841 0.1
Show the answer
0.841 0.1
At scale 1 the wave moves fast: sin(1) ≈ 0.841. At scale 10 it's slow: sin(0.1) ≈ 0.1. One position, two different wave values.
Why several speeds? One fast wave repeats every 2π ≈ 6.28 positions, so positions 0 and 6 get almost the same fast values. A slow wave changes too little to tell neighbors apart. Together they give every position its own pattern, the way a clock's second, minute and hour hands together give every moment its own reading.
Here are the codes for the first 8 positions: a fast wave (p ÷ 1) and a slow one (p ÷ 10), a sin and a cos of each.
import math
for p inrange(8):
code = []
for s in [1, 10]:
code.append(round(math.sin(p / s), 2))
code.append(round(math.cos(p / s), 2))
print(p, code)
Each line is one position's code: four numbers, each between −1 and 1, however far into the sentence the position is. The picture below stands each line on end, as a column. Read across a row to follow one wave from position 0 to 7.
Drill
Wave codes for positions
Set fast and slow to lists of sin(p / 1) and sin(p / 10) for positions 0 to 5, each rounded to 3 places. Then set climb to how far the slow wave rises from position 0 to position 5: slow[5] - slow[0], rounded to 3 places.
import math
fast = []
slow = []
for p inrange(5):
fast.append(round(math.sin(p * 1), 3))
slow.append(round(math.sin(p * 10), 3))
climb = 0print(fast, slow, climb)
In the lesson, your code is checked as you write it.
In the real tools. In PyTorch, the library most models are built with, the whole table comes from one line: a column of positions times a row of speeds gives every position at every speed, and torch.sin takes the sine of all of them at once. Here are your table's two sin rows, sin p and sin(p/10), with each position on a line of its own:
In your own words
Why does a transformer use waves of several speeds for positions, instead of just the position number?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write