---
title: "Lab: AC power in Python"
heading: Complex power, power-factor correction and three phases, computed
eyebrow: A3 · Lesson 26 · Lab: AC power in Python
xp: 60
---

::: hook
Utilities bill industrial customers for poor power factor, three-phase systems need their neutral currents checked, and every power supply's harmonics have to be counted. All of it is arithmetic with phasors, which makes it a natural job for Python. In this lab you'll compute complex power from voltage and current, size a correction capacitor, build a three-phase system as a list of phasors, and check the formula for the RMS of a signal with several frequencies against a direct calculation. If you haven't started A4 yet, its lessons on functions, loops and lists (lessons 1 to 8) cover the Python used here.
:::

::: play
- A load takes real power $P$, in kW, at a power factor that you set. The arrows are the power triangle: real power along the axis, reactive power up, and the apparent power as the long side.
- Add correction: a capacitor supplies reactive power $Q_C$ that points down, shortening the triangle's vertical side.
- Find the $Q_C$ that makes the power factor 1. How much shorter is the apparent power arrow?
:::

```sim plot
view: complex
range: 6
slider: P = 1..6 = 4 step 0.5
slider: pf = 0.5..1 = 0.75 step 0.01
slider: Qc = 0..10 = 0 step 0.1
arrow: P | label: P
arrow: j*P*tan(acos(pf)) | from: P | color: ch2 | label: Q of the load
arrow: -j*Qc | from: P + j*P*tan(acos(pf)) | color: ch3 | label: capacitor
arrow: P + j*(P*tan(acos(pf)) - Qc) | color: ch4 | label: S
readout: power factor now = P/sqrt(P^2 + (P*tan(acos(pf)) - Qc)^2) | digits: 4
readout: Qc for unity, kvar = P*tan(acos(pf)) | digits: 4
```

::: predict
## A 5 kW load at power factor 0.8 is corrected to 1. By what factor does the current it draws from the line fall?

- [ ] It doesn't change, since the power is the same
- [x] To 0.8 of what it was
- [ ] To 0.64 of what it was
- [ ] To half

::: reveal
To 0.8 of what it was. The line current is set by the apparent power, $|S| = P/\text{pf}$. Correction leaves $P$ alone and shrinks $|S|$ from $5/0.8 = 6.25$ kVA to 5 kVA, a factor of 0.8. The losses in the wiring go as the current squared, so they fall to 0.64 of what they were, which is why utilities care.
:::
:::

::: nameit
## Complex power in Python

With RMS phasors, $S = VI^*$, which in Python is `S = V * I.conjugate()`. Then:
- real power $P$ = `S.real`, in watts;
- reactive power $Q$ = `S.imag`, in vars, positive for an inductive load;
- apparent power $|S|$ = `abs(S)`, in VA;
- power factor = $P/|S|$.

With amplitude phasors, use $S = \tfrac12VI^*$ instead.

## Correcting the power factor

A capacitor across the load supplies reactive power $Q_C = V^2\omega C$. To bring the power factor from $\cos\varphi_1$ to $\cos\varphi_2$, it must supply $Q_C = P(\tan\varphi_1 - \tan\varphi_2)$, so

$$C = \frac{P(\tan\varphi_1 - \tan\varphi_2)}{2\pi fV^2}$$

## Three phases as a list

A balanced set of phase voltages is three phasors $V_p\angle 0°$, $V_p\angle{-120°}$ and $V_p\angle 120°$. The line voltages are the differences between pairs, and the neutral current is the sum of the three phase currents. A list and a loop handle any number of phases or any imbalance.

## RMS of several frequencies

For a signal made of a DC part and sinusoids at different frequencies, the mean squares add:

$$V_\text{rms}^2 = V_0^2 + \frac{A_1^2}{2} + \frac{A_2^2}{2} + \cdots$$

A direct check samples one full period of the slowest component, squares, averages and takes the root.
:::

::: example
## A load on 230 V RMS draws $5\angle{-30°}$ A RMS. Find $S$, $P$, $Q$ and the power factor.

::: solution
1. **Complex power.**
   $$\begin{aligned} S &= VI^* \\ &= 230 \times 5\angle 30° \\ &= 1150\angle 30°\ \text{VA} \\ &= 996 + j575\ \text{VA} \end{aligned}$$
2. **Real and reactive power.** The load takes 996 W of real power and 575 var of reactive power.
3. **Power factor.**
   $$\cos 30° = 0.866$$
   lagging.

**Answer:** $S = 1150\angle 30°$ VA, $P$ = 996 W, $Q$ = 575 var, and the power factor is 0.866 lagging.
:::
:::

::: example
## A 5 kW load at power factor 0.8 is on 230 V, 50 Hz. What capacitor brings it to unity?

::: solution
1. **Load angle.**
   $$\begin{aligned} \tan\varphi_1 &= \tan(\arccos 0.8) \\ &= 0.75 \end{aligned}$$
2. **Reactive power to cancel.**
   $$\begin{aligned} Q_C &= 5000 \times 0.75 \\ &= 3750\ \text{var} \end{aligned}$$
3. **Capacitor.**
   $$\begin{aligned} C &= \frac{3750}{2\pi \times 50 \times 230^2}\ \text{F} \\ &= 225.6\ \mu\text{F} \end{aligned}$$

**Answer:** a 225.6 µF capacitor brings it to unity.
:::
:::

::: example
## A 120 V phase system has phase currents of 10 A, 8 A and 6 A, each in phase with its own voltage. What flows in the neutral?

::: solution
1. **Add the real parts.** Adding $10\angle 0°$, $8\angle{-120°}$ and $6\angle 120°$, the real parts give
   $$10 - 4 - 3 = 3$$
2. **Add the imaginary parts.**
   $$-6.928 + 5.196 = -1.732$$
3. **Size of the neutral current.**
   $$\begin{aligned} |I_n| &= \sqrt{3^2 + 1.732^2} \\ &= 3.46\ \text{A} \end{aligned}$$
   at $-30°$.

**Answer:** 3.46 A flows in the neutral, at $-30°$.
:::
:::

::: check
given: P = 2 | 5 | 10; pf = 0.7 | 0.8; V = 120 | 230; f = 50 | 60
answer: P*1e3*tan(acos(pf))/(2*pi*f*V^2)
unit: F
tolerance: 0.5%

## A {P} kW load at power factor {pf} is on {V} V RMS, {f} Hz. What capacitance corrects it to unity?

::: right
Right. $Q_C = P\tan\varphi$ and $C = Q_C/(2\pi fV^2)$ = {answer}.
:::

::: misses
- [P*1e3*sin(acos(pf))/(2*pi*f*V^2)] Use $\tan\varphi$, which gives the reactive power from the real power.
- [P*1e3*tan(acos(pf))/(2*pi*f*V)] A capacitor's reactive power is $V^2\omega C$: the voltage is squared.
- [any] Not yet. Find the load's reactive power, then the capacitance that supplies it.
:::
:::

::: check
given: V0 = 5 | 12; A1 = 1 | 2; A2 = 0.5 | 3
answer: sqrt(V0^2 + (A1^2 + A2^2)/2)
unit: V
tolerance: 0.5%

## A signal is {V0} V DC plus {A1} V amplitude at 1 kHz plus {A2} V amplitude at 3 kHz. What is its RMS value?

::: right
Right. The mean squares add: $\sqrt{V_0^2 + (A_1^2 + A_2^2)/2}$ = {answer}.
:::

::: misses
- [V0 + (A1 + A2)/sqrt(2)] The parts add as squares.
- [any] Not yet. Add $V_0^2$ and each $A^2/2$, then take the root.
:::
:::

::: check
kind: python

## Write `complex_power(V, I)`, taking RMS phasors and returning `(P, Q, pf)`.

```python starter
import cmath, math

def complex_power(V, I):
    return 0, 0, 1

print(complex_power(230, cmath.rect(5, math.radians(-30))))
```

```python solution
import cmath, math

def complex_power(V, I):
    S = V * I.conjugate()
    return S.real, S.imag, S.real / abs(S)

print(complex_power(230, cmath.rect(5, math.radians(-30))))
```

```python tests
import cmath, math
P, Q, pf = complex_power(230, cmath.rect(5, math.radians(-30)))
assert abs(P - 995.929) < 1e-3 and abs(Q - 575) < 1e-9 and abs(pf - 0.866025) < 1e-6, f"230 V with 5 A lagging 30 degrees: 995.9 W, 575 var, pf 0.866; got {P}, {Q}, {pf}."
P, Q, pf = complex_power(cmath.rect(120, math.radians(20)), cmath.rect(2, math.radians(50)))
assert abs(Q + 120) < 1e-9, f"A current leading by 30 degrees means negative Q: -120 var; got {Q}."
P, Q, pf = complex_power(100, 3 + 0j)
assert abs(P - 300) < 1e-12 and abs(Q) < 1e-12 and abs(pf - 1) < 1e-12, "A resistive load has Q = 0 and pf = 1."
```

::: right
Right. The conjugate is what makes the angle come out as voltage minus current, the angle that sets the power factor.
:::
:::

::: check
kind: python

## Write `correction_C(P, pf_now, pf_target, V, f)`, returning the capacitance that raises a lagging load's power factor from `pf_now` to `pf_target`.

```python starter
import math

def correction_C(P, pf_now, pf_target, V, f):
    return 0

print(correction_C(5000, 0.8, 1, 230, 50))
```

```python solution
import math

def correction_C(P, pf_now, pf_target, V, f):
    Qc = P * (math.tan(math.acos(pf_now)) - math.tan(math.acos(pf_target)))
    return Qc / (2 * math.pi * f * V * V)

print(correction_C(5000, 0.8, 1, 230, 50))
```

```python tests
import math
C = correction_C(5000, 0.8, 1, 230, 50)
assert abs(C - 225.645e-6) < 1e-9, f"5 kW at 0.8 on 230 V, 50 Hz needs 225.6 uF; got {C * 1e6:.2f} uF."
C = correction_C(5000, 0.8, 0.95, 230, 50)
assert abs(C - 5000 * (0.75 - math.tan(math.acos(0.95))) / (2 * math.pi * 50 * 230 ** 2)) < 1e-12, "Correcting only to 0.95 needs less: subtract the reactive power still allowed."
assert correction_C(1000, 1, 1, 120, 60) == 0, "A load already at unity needs no capacitor."
```

::: right
Right. Correcting to 0.95 instead of 1 takes a little over half the capacitance here, which is why utilities usually ask for 0.95.
:::
:::

::: check
kind: python

## Write `phases(Vp)`, returning the list of three phasors $V_p\angle 0°$, $V_p\angle{-120°}$, $V_p\angle 120°$; `line_voltage(a, b)`, returning `abs(a - b)`; and `neutral(currents)`, returning the size of the sum of a list of phasors.

```python starter
import cmath, math

def phases(Vp):
    return [Vp, Vp, Vp]

def line_voltage(a, b):
    return 0

def neutral(currents):
    return 0

ph = phases(120)
print(line_voltage(ph[0], ph[1]), neutral([10, cmath.rect(8, math.radians(-120)), cmath.rect(6, math.radians(120))]))
```

```python solution
import cmath, math

def phases(Vp):
    return [cmath.rect(Vp, math.radians(a)) for a in (0, -120, 120)]

def line_voltage(a, b):
    return abs(a - b)

def neutral(currents):
    return abs(sum(currents))

ph = phases(120)
print(line_voltage(ph[0], ph[1]), neutral([10, cmath.rect(8, math.radians(-120)), cmath.rect(6, math.radians(120))]))
```

```python tests
import cmath, math
ph = phases(120)
assert len(ph) == 3 and abs(ph[1] - cmath.rect(120, math.radians(-120))) < 1e-9, "The second phase should be 120 at -120 degrees."
assert abs(line_voltage(ph[0], ph[1]) - 207.846) < 1e-3, f"120 V phases give 207.8 V between lines; got {line_voltage(ph[0], ph[1])}."
assert neutral(phases(10)) < 1e-12, "Balanced currents cancel in the neutral."
n = neutral([10, cmath.rect(8, math.radians(-120)), cmath.rect(6, math.radians(120))])
assert abs(n - math.sqrt(12)) < 1e-9, f"10, 8 and 6 A in phase with their voltages leave 3.46 A in the neutral; got {n}."
```

::: right
Right. The same three functions handle a 400 V European supply, a 480 V plant, or any imbalance you care to try.
:::
:::

::: check
kind: python

## Write `rms_by_samples(V0, parts, f1, N)`. `parts` is a list of `(A, f)` pairs, sinusoids $A\cos 2\pi ft$ added to the DC level `V0`, all with frequencies that are whole multiples of `f1`. Sample one period of `f1` at `N` evenly spaced times, square, average and take the root. The test compares it with the formula.

```python starter
import math

def rms_by_samples(V0, parts, f1, N):
    return V0

print(rms_by_samples(5, [(1, 120)], 120, 1000))
```

```python solution
import math

def rms_by_samples(V0, parts, f1, N):
    total = 0
    for k in range(N):
        t = k / (N * f1)
        v = V0 + sum(A * math.cos(2 * math.pi * f * t) for A, f in parts)
        total += v * v
    return math.sqrt(total / N)

print(rms_by_samples(5, [(1, 120)], 120, 1000))
```

```python tests
import math
r = rms_by_samples(5, [(1, 120)], 120, 1000)
assert abs(r - math.sqrt(25 + 0.5)) < 1e-9, f"5 V DC with 1 V of 120 Hz ripple is 5.050 V RMS; got {r}."
r = rms_by_samples(0, [(2, 1000), (1, 3000)], 1000, 64)
assert abs(r - math.sqrt(2.5)) < 1e-9, f"2 V at 1 kHz plus 1 V at 3 kHz is 1.581 V RMS; got {r}."
r = rms_by_samples(3, [(4, 50), (2, 150), (1, 250)], 50, 500)
assert abs(r - math.sqrt(9 + (16 + 4 + 1) / 2)) < 1e-9, "Each part adds its own mean square."
```

::: right
Right. The samples agree with the formula to rounding error, because over a whole period every cross term between different frequencies averages to exactly zero.
:::
:::

::: explain
## A factory is billed for reactive power even though reactive power does no work. Why does it cost the utility anything?

::: model
Reactive power is energy that sloshes back and forth between the source and the load's magnetic or electric fields twice each cycle, doing no net work. But to carry it, current has to flow: the line current is set by the apparent power $|S| = \sqrt{P^2 + Q^2}$, and with $Q$ present it's larger than the real power alone requires. That extra current heats every wire and transformer between the generator and the factory, as $I^2R$, and it takes up capacity that could have carried real power to someone else, so the utility must build bigger equipment to deliver the same useful energy. Correcting the power factor with capacitors near the load supplies the reactive power locally, so it no longer travels through the grid.
:::
:::

::: practice

::: check
given: P = 0.5..50; pf = 0.5..0.95; V = 100..480; f = 50 | 60
answer: P*1e3*tan(acos(pf))/(2*pi*f*V^2)
unit: F
tolerance: 0.5%

## Correction capacitor, in farads: {P} kW at pf {pf}, {V} V RMS, {f} Hz?

::: misses
- [any] $P\tan\varphi/(2\pi fV^2)$.
:::
:::

::: check
given: V0 = 0..20; A1 = 0.1..10; A2 = 0.1..10
answer: sqrt(V0^2 + (A1^2 + A2^2)/2)
tolerance: 0.5%

## RMS of {V0} V DC + {A1} V and {A2} V amplitude at two frequencies?

::: misses
- [any] $\sqrt{V_0^2 + (A_1^2 + A_2^2)/2}$.
:::
:::
:::
