Time for action – sorting complex numbers
We will create an array of complex numbers and sort it:
- Generate five random numbers for the real part of the complex numbers and five numbers for the imaginary part. Seed the random generator to
42
:np.random.seed(42) complex_numbers = np.random.random(5) + 1j * np.random.random(5) print("Complex numbers\n", complex_numbers)
- Call the
sort_complex()
function to sort the complex numbers we generated in the previous step:print("Sorted\n", np.sort_complex(complex_numbers))
The sorted numbers would be:
Sorted [ 0.39342751+0.34955771j 0.40597665+0.77477433j 0.41516850+0.26221878j 0.86631422+0.74612422j 0.92293095+0.81335691j]
What just happened?
We generated random complex numbers and sorted them using the sort_complex()
function (see sortcomplex.py
):
from __future__ import print_function import numpy as np np.random.seed(42) complex_numbers = np.random.random(5) + 1j * np.random.random(5) print("Complex numbers\n"...