---
title: "Lab: measuring sine waves in Python"
heading: What a digital oscilloscope does with its samples
eyebrow: A2 · Lesson 19 · Lab: measuring sine waves
xp: 60
---

::: hook
A digital oscilloscope never sees a smooth sine wave. It sees a list of numbers, samples taken thousands or millions of times a second, and every measurement it shows you (amplitude, RMS, frequency, phase) is computed from that list. In this lab you'll write those measurements yourself in Python, using only loops, lists and the `math` module. If you haven't started A4 yet, its lessons on functions, loops and lists (lessons 1 to 9) cover everything used here.
:::

::: play
- The stems are $N$ samples spread evenly over one cycle of $A\cos(\theta + \varphi)$. The dashed curve is the wave they came from.
- Change $N$, the amplitude and the phase. The samples land in different places on the curve.
- Watch the readout of the samples' RMS. Does it depend on where the samples land?
:::

```sim plot
view: graph
x: n = 0..32
y: v = -2.2..2.2 V
slider: N = 3..32 step 1 = 8
slider: A = 0.5..2 = 1 V
slider: p = -180..180 = 0
plot: A*cos(2*pi*n/N + p*pi/180)*step(N - 0.5 - n) | stems | label: samples
plot: A*cos(2*pi*n/N + p*pi/180) | samples: 400 | dashed | color: ch2 | label: the wave
readout: A/√2, V = A/sqrt(2) | digits: 4
```

::: predict
## Eight samples are spread evenly over exactly one cycle of a 1 V sine wave. What is their RMS?

- [x] Exactly 0.7071 V, wherever the samples land
- [ ] A little less than 0.7071 V, since the samples miss the peaks
- [ ] A little more than 0.7071 V
- [ ] It depends on the phase

::: reveal
It's exactly 0.7071 V. The squares of evenly spaced samples of a cosine always average to exactly ½ over a whole cycle, as long as there are at least three samples per cycle: $\cos^2\theta = \tfrac12 + \tfrac12\cos 2\theta$, and the $\cos 2\theta$ terms cancel when added around the circle. Samples that miss the peaks are made up for by others that land on the steep parts. Over a fraction of a cycle the same measurement would be off, which is why scopes measure over whole cycles.
:::
:::

::: nameit
## Samples in a list

A wave sampled at rate $f_s$ is recorded at the times $t_n = n/f_s$. In Python, a list comprehension builds the whole record in one line:

```python
v = [A * math.cos(2 * math.pi * f * n / fs + phi) for n in range(N)]
```

## RMS

The RMS of a list is the square root of the mean of the squares:

$$V_\text{rms} = \sqrt{\frac{1}{N}\sum_{n=0}^{N-1} v_n^2}$$

Over whole cycles of a sine wave this gives $A/\sqrt{2}$.

## Zero crossings and frequency

An upward zero crossing lies between a negative sample $v_n$ and a non-negative one $v_{n+1}$. Drawing a straight line between them puts the crossing at

$$t = \frac{1}{f_s}\left(n + \frac{-v_n}{v_{n+1} - v_n}\right)$$

The time from the first upward crossing to the last, divided by the number of cycles between them, is the period.

## Amplitude and phase from sums

Multiply each sample of one cycle by a cosine and by a sine at the same frequency, and add:

$$I = \frac{2}{N}\sum_n v_n\cos\frac{2\pi n}{N}, \qquad Q = \frac{2}{N}\sum_n v_n\sin\frac{2\pi n}{N}$$

For $v_n = A\cos(2\pi n/N + \varphi)$, these give $I = A\cos\varphi$ and $Q = -A\sin\varphi$, so $A = \sqrt{I^2 + Q^2}$ and $\varphi$ is the angle of the point $(I, -Q)$. In Python that angle is `math.atan2(-Q, I)`, which picks the right quadrant. This is how lock-in amplifiers and network analyzers measure phase.
:::

::: example
## The four samples 0, 1, 0, −1 cover one cycle of a sine wave. What are their RMS and the wave's amplitude?

::: solution
1. **Average the squares.** The squares are 0, 1, 0 and 1, which average to
   $$\frac{2}{4} = 0.5$$
2. **RMS.**
   $$\sqrt{0.5} = 0.707$$
3. **Amplitude.**
   $$0.707 \times \sqrt{2} = 1$$
   Four samples are enough, even though two of them are zero.

**Answer:** the RMS is 0.707, and the amplitude is 1.
:::
:::

::: example
## A record sampled every 0.1 ms has $-0.3$ V at $t$ = 1.0 ms and $0.5$ V at $t$ = 1.1 ms. Where does the wave cross zero?

::: solution
1. **Compare the rises.** The voltage rises by 0.8 V over 0.1 ms, and it has to rise 0.3 V to reach zero.
2. **Fraction of the way.**
   $$\frac{0.3}{0.8} = 0.375$$
3. **Crossing time.**
   $$\begin{aligned} t &= 1.0 + 0.375 \times 0.1 \\ &= 1.0375\ \text{ms} \end{aligned}$$

**Answer:** the wave crosses zero at 1.0375 ms.
:::
:::

::: example
## One cycle is sampled four times: 1.414, −1.414, −1.414, 1.414. Find the amplitude and phase from the sums $I$ and $Q$.

::: solution
1. **List the cosines and sines.** With $N = 4$, the cosines at $n = 0, 1, 2, 3$ are $1, 0, -1, 0$ and the sines are $0, 1, 0, -1$.
2. **The sum I.**
   $$\begin{aligned} I &= \tfrac24(1.414 + 0 + 1.414 + 0) \\ &= 1.414 \end{aligned}$$
3. **The sum Q.**
   $$\begin{aligned} Q &= \tfrac24(0 - 1.414 + 0 - 1.414) \\ &= -1.414 \end{aligned}$$
4. **Amplitude.**
   $$\begin{aligned} A &= \sqrt{1.414^2 + 1.414^2} \\ &= 2 \end{aligned}$$
5. **Phase.** The angle of $(I, -Q) = (1.414, 1.414)$ is 45°.

**Answer:** the amplitude is 2 and the phase is 45°: the samples came from $2\cos(\theta + 45°)$.
:::
:::

::: check
given: A = 1 | 2.5 | 10; N = 4 | 8 | 100
answer: A/sqrt(2)
unit: V
tolerance: 0.5%

## {N} samples are spread evenly over exactly one cycle of a sine wave of amplitude {A} V. What is their RMS?

::: right
Right. Over whole cycles, $A/\sqrt{2}$ = {answer}, however many samples there are (three or more).
:::

::: misses
- [A] That's the peak.
- [A/2] The mean square is $A^2/2$; take its square root.
- [any] Not yet. The mean of $\cos^2$ over a cycle is ½.
:::
:::

::: check
given: t0 = 1 | 2.5; dt = 0.1 | 0.05; a = 0.2 | 0.6; b = 0.4 | 0.9
answer: t0 + dt*a/(a + b)
unit: s
tolerance: 0.1%

## Two neighboring samples are $-\given{a}$ V at $t$ = {t0} s and $\given{b}$ V at $t = \given{t0} + \given{dt}$ s. Where does a straight line between them cross zero?

::: right
Right. It has to rise {a} V of the whole rise, so the crossing is at {answer} s.
:::

::: misses
- [t0 + dt*b/(a + b)] That measures from the wrong end: the line starts at $-\given{a}$ V.
- [t0 + dt/2] The crossing is halfway only when the two samples are equal and opposite.
- [any] Not yet. Find the fraction of the rise needed to reach zero.
:::
:::

::: check
kind: python

## Write `samples(A, f, phi_deg, fs, N)`, returning a list of the `N` values $A\cos(2\pi f n/f_s + \varphi)$ for $n = 0, 1, \ldots, N - 1$, with the phase given in degrees. Then write `rms(v)`.

```python starter
import math

def samples(A, f, phi_deg, fs, N):
    return [0] * N

def rms(v):
    return 0

v = samples(2, 50, 0, 1000, 20)
print(v[:5], rms(v))
```

```python solution
import math

def samples(A, f, phi_deg, fs, N):
    phi = math.radians(phi_deg)
    return [A * math.cos(2 * math.pi * f * n / fs + phi) for n in range(N)]

def rms(v):
    return math.sqrt(sum(x * x for x in v) / len(v))

v = samples(2, 50, 0, 1000, 20)
print(v[:5], rms(v))
```

```python tests
import math
v = samples(2, 50, 0, 1000, 20)
assert len(v) == 20, "There should be N samples."
assert abs(v[0] - 2) < 1e-12 and abs(v[5]) < 1e-12 and abs(v[10] + 2) < 1e-12, "At 20 samples a cycle, sample 5 is a quarter cycle (zero) and sample 10 half a cycle (-2)."
w = samples(1, 1, 90, 4, 4)
assert all(abs(a - b) < 1e-12 for a, b in zip(w, [0, -1, 0, 1])), f"A 90 degree phase turns the cosine into -sin; got {w}."
assert abs(rms([0, 1, 0, -1]) - math.sqrt(0.5)) < 1e-12, "The RMS of 0, 1, 0, -1 is 0.7071."
assert abs(rms(samples(3, 60, 37, 6000, 300)) - 3 / math.sqrt(2)) < 1e-12, "Over whole cycles, the RMS should be A divided by the square root of 2."
```

::: right
Right. Try a record that ends partway through a cycle and watch the RMS drift away from $A/\sqrt{2}$.
:::
:::

::: check
kind: python

## Write `up_crossings(v, fs)`, returning the times of every upward zero crossing (a negative sample followed by one that's zero or positive), found by straight-line interpolation. Then write `frequency(v, fs)`, which uses the first and last crossings to measure the frequency.

```python starter
import math

def up_crossings(v, fs):
    return []

def frequency(v, fs):
    return 0

v = [2 * math.cos(2 * math.pi * 50 * n / 10000 + math.radians(30)) for n in range(1000)]
print(up_crossings(v, 10000), frequency(v, 10000))
```

```python solution
import math

def up_crossings(v, fs):
    times = []
    for n in range(len(v) - 1):
        if v[n] < 0 <= v[n + 1]:
            times.append((n + -v[n] / (v[n + 1] - v[n])) / fs)
    return times

def frequency(v, fs):
    t = up_crossings(v, fs)
    return (len(t) - 1) / (t[-1] - t[0])

v = [2 * math.cos(2 * math.pi * 50 * n / 10000 + math.radians(30)) for n in range(1000)]
print(up_crossings(v, 10000), frequency(v, 10000))
```

```python tests
import math
v = [2 * math.cos(2 * math.pi * 50 * n / 10000 + math.radians(30)) for n in range(1000)]
t = up_crossings(v, 10000)
assert len(t) == 5, f"Five cycles of 50 Hz should cross zero going up five times; got {len(t)}."
assert abs(t[0] - 0.013333) < 1e-5, f"The first upward crossing is at 13.33 ms; got {t[0] * 1000:.4f} ms."
assert abs(frequency(v, 10000) - 50) < 1e-3, f"The frequency should come out at 50 Hz; got {frequency(v, 10000)}."
w = [math.sin(2 * math.pi * 1234.5 * n / 48000) for n in range(4800)]
assert abs(frequency(w, 48000) - 1234.5) < 0.05, f"A 1234.5 Hz tone sampled at 48 kHz should measure 1234.5 Hz; got {frequency(w, 48000)}."
c = up_crossings([1, 2, -1, -2, 1], 1)
assert len(c) == 1 and abs(c[0] - (3 + 2 / 3)) < 1e-12, "Only the rise from -2 to 1 is an upward crossing, two thirds of the way along."
```

::: right
Right. Interpolating between samples measures the frequency far more finely than the sample spacing alone would.
:::
:::

::: check
kind: python

## Write `amplitude_phase(v)` for a list `v` holding exactly one cycle. It forms the sums $I$ and $Q$ from the reading above and returns `(A, phi_deg)`, the amplitude and the phase in degrees, using `math.atan2(-Q, I)` for the angle.

```python starter
import math

def amplitude_phase(v):
    return max(v), 0

v = [1.5 * math.cos(2 * math.pi * n / 64 - math.radians(40)) for n in range(64)]
print(amplitude_phase(v))
```

```python solution
import math

def amplitude_phase(v):
    N = len(v)
    I = 2 / N * sum(x * math.cos(2 * math.pi * n / N) for n, x in enumerate(v))
    Q = 2 / N * sum(x * math.sin(2 * math.pi * n / N) for n, x in enumerate(v))
    return math.hypot(I, Q), math.degrees(math.atan2(-Q, I))

v = [1.5 * math.cos(2 * math.pi * n / 64 - math.radians(40)) for n in range(64)]
print(amplitude_phase(v))
```

```python tests
import math
for A, p, N in [(1.5, -40, 64), (2, 135, 8), (0.3, -170, 5), (4, 0, 100)]:
    v = [A * math.cos(2 * math.pi * n / N + math.radians(p)) for n in range(N)]
    a, q = amplitude_phase(v)
    assert abs(a - A) < 1e-9 and abs(q - p) < 1e-9, f"A = {A} at {p} degrees with {N} samples should come back exactly; got {a:.6f} at {q:.4f} degrees."
v = [math.cos(2 * math.pi * n / 50) + 0.5 for n in range(50)]
a, q = amplitude_phase(v)
assert abs(a - 1) < 1e-9 and abs(q) < 1e-9, "A DC offset shouldn't change the measured amplitude or phase."
```

::: right
Right. The sums ignore any DC level and any harmonics, so this picks out one frequency even from a messy signal.
:::
:::

::: explain
## A scope measures a sine wave's RMS from a record that holds three and a half cycles, and reads a little off. Why, and what does measuring over whole cycles fix?

::: model
The RMS averages $v^2$, and for a sine wave $v^2 = \frac{A^2}{2}(1 + \cos 2\theta)$: a constant $A^2/2$ plus a ripple at twice the frequency. Over whole cycles the ripple averages to exactly zero, leaving $A^2/2$, so the RMS is exactly $A/\sqrt{2}$. A record of three and a half cycles includes a leftover half cycle, and the ripple over that piece doesn't average to zero, so it adds or takes away a little depending on where the record starts. The error shrinks as the record gets longer, since the leftover piece is a smaller share of the whole. Cutting the record to whole cycles, found from the zero crossings, removes it entirely, which is why scopes and meters measure "over an integer number of cycles".
:::
:::

::: practice

::: check
given: A = 0.1..100
answer: A/sqrt(2)
tolerance: 0.5%

## RMS of a sine wave of amplitude {A}, over whole cycles?

::: misses
- [any] $A/\sqrt{2}$.
:::
:::

::: check
given: t0 = 0..10; dt = 0.01..1; a = 0.1..2; b = 0.1..2
answer: t0 + dt*a/(a + b)
tolerance: 0.1%

## Samples $-\given{a}$ at {t0} and $\given{b}$ at $\given{t0} + \given{dt}$: where's the zero crossing?

::: misses
- [any] $t_0 + \Delta t \cdot a/(a + b)$.
:::
:::
:::
