Time for action – sorting complex numbers

We will create an array of complex numbers and sort it. Perform the following steps to do so:

  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
    ", complex_numbers
  2. Call the sort_complex function to sort the complex numbers we generated in the previous step.
    print "Sorted
    ", np.sort_complex(complex_numbers)

    The sorted numbers would be shown as follows:

    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).

import numpy as np

np.random.seed(42)
complex_numbers = np.random.random(5) + 1j * np.random.random(5)
print "Complex numbers
", complex_numbers

print "Sorted
", np.sort_complex(complex_numbers)

Pop quiz – generating random numbers

Q1. Which NumPy module deals with random numbers?

  1. Randnum
  2. random
  3. randomutil
  4. rand
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.91.44