Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – sorting complex numbers


We will create an array of complex numbers and sort it:

  1. 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)
  2. 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", complex_numbers)

print("Sorted...