---
title: Arrays with NumPy
heading: Doing the same calculation on a million numbers at once
eyebrow: A4 · Lesson 28 · Arrays with NumPy
xp: 40
---

::: hook
A scope captures a waveform as thousands of samples. To find its RMS value you square every sample, average them and take the square root. With NumPy, that's one line, and it doesn't care whether there are ten samples or ten million.
:::

::: predict
## With `import numpy as np`, what does `np.array([1, 2, 3]) * 2` give?

- [ ] `[1, 2, 3, 1, 2, 3]`
- [x] `array([2, 4, 6])`
- [ ] `12`
- [ ] An error

::: reveal
`array([2, 4, 6])`. Arithmetic on a NumPy array acts on every element at once. A plain Python list behaves differently: `[1, 2, 3] * 2` repeats the list, giving `[1, 2, 3, 1, 2, 3]`. That difference is why engineering code uses arrays.
:::
:::

::: nameit
## Arrays act element by element

`import numpy as np` brings in NumPy. Its arrays hold many numbers and do arithmetic on all of them together:

```
import numpy as np
t = np.linspace(0, 0.02, 1001)        # 1001 times from 0 to 20 ms
v = 5 * np.sin(2 * np.pi * 50 * t)     # a 50 Hz sine, sampled at each time
```

`np.linspace(a, b, n)` gives n evenly spaced values from a to b, both ends included. `np.arange(a, b, step)` steps from a up to, but not including, b. NumPy's functions, `np.sin`, `np.exp`, `np.sqrt`, `np.log10` and the rest, work on whole arrays.

**Reducing an array to one number:** `v.max()`, `v.min()`, `v.mean()`, `v.sum()`, and `len(v)` for how many there are. The RMS value is

```
rms = np.sqrt(np.mean(v**2))
```

which reads exactly like its name: the root of the mean of the squares.

**Picking elements.** `v[0]` is the first element and `v[-1]` the last; `v[10:20]` is elements 10 to 19. A comparison gives an array of True and False, which can pick elements or be counted:

```
high = v > 2.5          # True where the voltage is above 2.5 V
np.mean(high)           # the fraction of samples above it
v[high]                 # just those samples
```

**Finding things.** `np.argmax(v)` is the index of the largest element and `np.argmin(np.abs(x - target))` the index of the element nearest a target.
:::

::: example
## A 10 V amplitude, 50 Hz sine drives a 100 Ω resistor. Find the average power and the fraction of time the voltage is above 5 V in size.

::: solution
1. **Sample one period and work on whole arrays.** Each line acts on all 2001 samples at once.

```
import numpy as np
t = np.linspace(0, 0.02, 2001)          # one period
v = 10 * np.sin(2 * np.pi * 50 * t)
P = np.mean(v**2) / 100                 # about 0.5 W
frac = np.mean(np.abs(v) > 5)           # about 0.667
```

2. **The average power.** The mean of $v^2$ is half the amplitude squared:
   $$\begin{aligned} \overline{v^2} &= A^2/2 \\ &= 50\ \text{V}^2 \end{aligned}$$
   so 50 over 100 Ω is 0.5 W.
3. **The fraction above 5 V.** $|\sin| > 0.5$ for two-thirds of each cycle.

**Answer:** the average power is 0.5 W, and the voltage is above 5 V in size two-thirds of the time.
:::
:::

::: example
## Find the times when a sampled signal first goes above a threshold.

::: solution
1. **Compare the whole array with the threshold.** `x >= 0.9` is an array of True and False.
2. **Find the first True.** `np.argmax` returns the first True, since True counts as 1.

```
t = np.linspace(0, 1, 1001)
x = 1 - np.exp(-t / 0.2)
i = np.argmax(x >= 0.9)          # index of the first True
print(t[i])                      # 0.461
```

3. **Check.** The exact answer is
   $$\begin{aligned} t &= 0.2\ln 10 \\ &= 0.4605 \end{aligned}$$

**Answer:** the signal first reaches 0.9 at the sample at $t = 0.461$, just past the exact 0.4605.
:::
:::

::: check
kind: python
given: A = 1..10 int; f = 50 | 60 | 100 | 400

## Make `t`, 2001 evenly spaced times from 0 to 0.05 s, and `v`, the voltage $\given{A}\sin(2\pi \cdot \given{f}\,t)$ at each of them. Then set `vmax` to the largest value in `v`.

`A` = {A} and `f` = {f} are already defined.

```python starter
import numpy as np

t = 0            # replace: 2001 times from 0 to 0.05 s
v = 0            # replace: A sin(2π f t) at each time
vmax = 0         # replace: the largest value in v
print(vmax)
```

```python solution
import numpy as np

t = np.linspace(0, 0.05, 2001)
v = A * np.sin(2 * np.pi * f * t)
vmax = v.max()
print(vmax)
```

```python tests
import numpy as np
assert np.shape(t) == (2001,), "t should hold 2001 values: np.linspace(0, 0.05, 2001)."
assert abs(t[-1] - 0.05) < 1e-12 and abs(t[0]) < 1e-12, "t should run from 0 to 0.05 s, both ends included."
assert np.shape(v) == (2001,), "v should have one value for each time in t."
assert np.allclose(v, A * np.sin(2 * np.pi * f * t)), "v doesn't match A·sin(2π f t) yet. Remember np.sin takes radians."
assert abs(vmax - v.max()) < 1e-12, "vmax should be the largest value in v."
```

::: right
Right. With 2001 samples over a few cycles, `vmax` lands within a whisker of the amplitude {A}.
:::
:::

::: check
kind: python
given: A = 1..20 int; f = 50 | 60 | 1000

## The samples in `v` cover exactly 4 cycles of a sine of amplitude {A}. Compute their RMS value as `rms`.

```python starter
import numpy as np

t = np.linspace(0, 4 / f, 4000, endpoint=False)
v = A * np.sin(2 * np.pi * f * t)

rms = 0   # replace this
print(rms, A / np.sqrt(2))
```

```python solution
import numpy as np

t = np.linspace(0, 4 / f, 4000, endpoint=False)
v = A * np.sin(2 * np.pi * f * t)

rms = np.sqrt(np.mean(v**2))
print(rms, A / np.sqrt(2))
```

```python tests
import numpy as np
assert abs(rms - np.mean(np.abs(v))) > 1e-6, "That's the average of the absolute values. RMS squares first: the root of the mean of the squares."
assert abs(rms - np.sqrt(np.mean(v**2))) < 1e-9, "rms should be np.sqrt(np.mean(v**2))."
assert abs(rms - A / np.sqrt(2)) < 1e-6 * A, "For whole cycles of a sine, the RMS should come out as A/√2."
```

::: right
Right. Over whole cycles, the root-mean-square of a sine is its amplitude over √2, as A2 promised.
:::
:::

::: check
kind: python
given: target = 1.1k..90k sig 2

## The array `E12` holds the E12 values in one decade. Set `nearest` to the E12 resistor, in ohms, nearest to `target` = {target} Ω. (Look in the decade that contains the target.)

```python starter
import numpy as np

E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, 10.0])
decade = 10 ** np.floor(np.log10(target))   # 1000 for a target of 4321, say
nearest = 0   # replace this
print(nearest)
```

```python solution
import numpy as np

E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, 10.0])
decade = 10 ** np.floor(np.log10(target))
values = E12 * decade
nearest = values[np.argmin(np.abs(values - target))]
print(nearest)
```

```python tests
import numpy as np
cands = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, 10.0]) * 10 ** np.floor(np.log10(target))
want = cands[np.argmin(np.abs(cands - target))]
assert nearest != 0, "Set nearest to one of the E12 values, scaled into the target's decade."
assert abs(nearest - want) < 1e-6 * want, f"nearest should be the E12 value closest to {target} Ω, which is {want:g} Ω."
```

::: right
Right. `np.argmin(np.abs(values - target))` finds the index of the smallest distance, a pattern you'll use constantly.
:::
:::

::: check
kind: choice

## For an array `v` of 1000 samples, what is `v[-1]`?

- [ ] An error, because indexes can't be negative
- [x] The last sample
- [ ] Every sample, negated
- [ ] The sample before the first

::: right
Right. Negative indexes count from the end: `v[-1]` is the last element and `v[-2]` the one before it.
:::

::: misses
- [1] Negative indexes are allowed: they count from the end.
- [3] Negating every element is `-v`. An index picks one element.
- [any] Negative indexes count back from the end of the array.
:::
:::

::: check
kind: python
given: A = 1..10 int; f = 1000 | 5000 | 20000

## The starter samples $\given{A}\sin(2\pi \cdot \given{f}\,t)$ V every 0.1 µs for one period. Use `np.diff` to set `slope` to the rate of change between successive samples (in volts per second), and `slew` to its largest size. Then set `rel` to how far `slew` is from the exact peak rate $2\pi f A$, as a fraction.

```python starter
import numpy as np
dt = 1e-7
t = np.arange(0, 1 / f, dt)
v = A * np.sin(2 * np.pi * f * t)
slope = np.diff(v)
slew = slope.max()
rel = 0
print(slew, rel)
```

```python solution
import numpy as np
dt = 1e-7
t = np.arange(0, 1 / f, dt)
v = A * np.sin(2 * np.pi * f * t)
slope = np.diff(v) / dt
slew = np.max(np.abs(slope))
rel = abs(slew - 2 * np.pi * f * A) / (2 * np.pi * f * A)
print(slew, rel)
```

```python tests
import numpy as np
dt = 1e-7
tt = np.arange(0, 1 / f, dt)
vv = A * np.sin(2 * np.pi * f * tt)
want = np.max(np.abs(np.diff(vv) / dt))
assert np.shape(slope) == (len(tt) - 1,), "np.diff gives one fewer value than the samples."
assert abs(slew - want) < 1e-6 * want, "slew is the largest size of np.diff(v) / dt: divide by the time step to get volts per second."
assert abs(rel - abs(want - 2 * np.pi * f * A) / (2 * np.pi * f * A)) < 1e-12 and rel < 1e-3, "rel compares slew with 2πfA."
```

::: right
Right. `np.diff(v) / dt` is the derivative estimate at every step at once. A sine's steepest slope, at its zero crossings, is $2\pi f A$: an amplifier must slew at least that fast to reproduce it.
:::
:::

::: check
kind: choice

## What is `len(np.arange(0, 1, 0.25))`?

- [x] 4
- [ ] 5
- [ ] 3
- [ ] 1

::: right
Right. `np.arange` stops before its end value, like `range`: 0, 0.25, 0.5 and 0.75. Use `np.linspace(0, 1, 5)` when you want the end included.
:::

::: misses
- [2] That would include 1.0, and `arange` stops before its end value.
- [3] 0.75 is still below 1, so it's included: 0, 0.25, 0.5, 0.75.
- [4] The third argument is the step, 0.25, so there are several values below 1.
:::
:::

::: explain
## Why does `np.sqrt(np.mean(v**2))` give the RMS value of a sampled waveform?

::: model
RMS stands for root mean square, and the expression does those steps from the inside out: `v**2` squares every sample, `np.mean` averages the squares, and `np.sqrt` takes the square root of that average. With samples spread evenly over whole cycles, the average of the samples is a good stand-in for the average over time, so the result matches the RMS of the continuous waveform.
:::
:::

::: practice

::: check
kind: python
given: A = 1..9 int; f = 50 | 60 | 400; th = 0.2..0.9 sig 1

## For 4000 samples of $\given{A}\sin(2\pi f t)$ over exactly 4 cycles, set `frac` to the fraction of samples above {th} × {A}.

```python starter
import numpy as np

t = np.linspace(0, 4 / f, 4000, endpoint=False)
v = A * np.sin(2 * np.pi * f * t)
frac = 0
print(frac)
```

```python solution
import numpy as np

t = np.linspace(0, 4 / f, 4000, endpoint=False)
v = A * np.sin(2 * np.pi * f * t)
frac = np.mean(v > th * A)
print(frac)
```

```python tests
import numpy as np
assert abs(frac - np.mean(v > th * A)) < 1e-12, "frac should be np.mean(v > th * A): the comparison gives True/False, and the mean counts the Trues."
```
:::

::: check
kind: python
given: n = 5..50 int

## Set `s` to the sum of the squares of the whole numbers from 1 to {n}, using `np.arange`.

```python starter
import numpy as np

s = 0
print(s)
```

```python solution
import numpy as np

s = np.sum(np.arange(1, n + 1) ** 2)
print(s)
```

```python tests
assert s == n * (n + 1) * (2 * n + 1) // 6, "Check the range: np.arange(1, n + 1) stops just before n + 1, so it includes n."
```
:::

::: check
kind: python
given: R = 10..1000 sig 2

## `I` holds 500 current samples. Set `P_avg` to the average power they deliver to a {R} Ω resistor.

```python starter
import numpy as np

I = 0.5 * np.sin(np.linspace(0, 20 * np.pi, 500, endpoint=False)) + 0.2
P_avg = 0
print(P_avg)
```

```python solution
import numpy as np

I = 0.5 * np.sin(np.linspace(0, 20 * np.pi, 500, endpoint=False)) + 0.2
P_avg = np.mean(I**2 * R)
print(P_avg)
```

```python tests
import numpy as np
assert abs(P_avg - np.mean(I) ** 2 * R) > 1e-9, "That squares the average current. Square each sample first: power is I² R at every instant."
assert abs(P_avg - np.mean(I**2 * R)) < 1e-9 * R, "P_avg should be the mean of I² R over the samples."
```
:::
:::
