A3 · Lesson 10 · Lab: complex numbers in Python
Python already speaks complex numbers
Python has complex numbers built in. Type 3+4j and you get the point , with the engineer's and everything. The cmath module adds the complex versions of sqrt, exp and the conversions to polar form. In this lab you'll use them to solve any quadratic, find all the roots of a complex number, and watch a ringing circuit's natural response decay exactly as its roots say it should. If you haven't started A4 yet, its lessons on functions, loops and lists (lessons 1 to 8) cover the Python used here.
- The curve is for a root : a ringing response.
- Move and . The dashed envelope is , and the curve rings at inside it.
- The readout gives the ratio of one peak to the next. It depends on and together, through .
Predict
What does Python print for (1j)**2?
It prints (-1+0j). Python keeps the result complex even when its imaginary part is zero, so it shows both parts. 1j is how Python writes alone; a bare j would be read as a variable name.
Name it
Complex numbers in Python
- Making one:
z = 3 + 4j, orcomplex(3, 4). Thejmust follow a number directly, so write1j, neverj. - Parts:
z.realis 3.0,z.imagis 4.0, andz.conjugate()is(3-4j). - Length:
abs(z)gives 5.0. - Arithmetic:
+,-,*,/and**all work as in the lessons.
The cmath module
import cmath adds:
cmath.phase(z): the angle in radians, from to (it uses atan2, so the quadrant is right);cmath.polar(z): the pair(r, angle);cmath.rect(r, angle): back from polar, with the angle in radians;cmath.exp(z),cmath.sqrt(z)andcmath.log(z): these accept complex numbers, where themathversions raise an error.
math.degrees and math.radians convert angles.
The pieces this lab builds
- Roots of : with
cmath.sqrt, the quadratic formula works whatever the sign of . - The roots of : for .
- A natural response: sampled at many times. Its successive peaks shrink by exactly , because they're one period, , apart.
Worked example
What does Python give for cmath.polar(-4+3j), and what is the angle in degrees?
Show the solution
- Python's answer. It gives
(5.0, 2.498...): the length is and the angle is 2.498 rad. - Convert to degrees.
math.degrees(2.498)is 143.13°, in the second quadrant where sits. - The wrong way. A plain
math.atan(3 / -4)would give , in the wrong quadrant.
Answer (5.0, 2.498...), a length of 5 and an angle of 2.498 rad, which is 143.13°.
Worked example
Find the cube roots of the way the lab's function will.
Show the solution
- Polar form. has length 8 and angle 90°.
- Length of the roots.
- Angles of the roots. For :
- Rectangular form. They're , and .
- Check in Python. Cubing any of them, as in
(-2j)**3, gives back8j(to rounding).
Answer the cube roots are , and .
Worked example
A response has per second. By what factor does each peak shrink?
Show the solution
- Time between peaks. The peaks are one period apart:
- Envelope over one period. Over that time the envelope falls by
Answer each peak is 60.7% of the one before.
Check
What does cmath.phase return for the complex number ?
Check
A natural response is with . What is the ratio of each peak to the one before?
Check
Write polar_deg(z), returning (r, degrees), and from_polar_deg(r, deg), returning the complex number. Use abs, cmath.phase, cmath.rect and math.radians/math.degrees.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write quadratic_roots(a, b, c), returning the two roots of as a pair, the one with the + sign first. Use cmath.sqrt so it works for any discriminant.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write nth_roots(z, n), returning a list of all n roots of z, in order of : length and angle , with = cmath.phase(z).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write peak_ratio(s, T, steps). It samples at steps evenly spaced times from 0 to T, finds the local maxima (samples bigger than both neighbors), and returns the average ratio of each peak to the one before. The test checks it against .
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
Why does math.sqrt(-4) raise an error while cmath.sqrt(-4) returns 2j? When is each the right tool?
The two modules answer different questions. math works only with real numbers, and no real number squares to −4, so it reports an error: in a calculation that's supposed to stay real, a negative under a root usually means a mistake, and failing loudly is helpful. cmath works in the complex plane, where every number has square roots, so it returns (and is the other root). In EE the complex answer is often the meaningful one: a circuit whose characteristic equation has a negative discriminant really does ring, at a frequency set by the imaginary part. Use math when a negative value would be a bug, and cmath when complex results are expected, such as roots of characteristic equations, impedances and phasors.
Practice
Keep practicing
4 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.