Skip to Content
Advanced Python Programming
book

Advanced Python Programming

by Dr. Gabriele Lanaro, Quan Nguyen, Sakis Kasampalis
February 2019
Intermediate to advanced
672 pages
16h 50m
English
Packt Publishing
Content preview from Advanced Python Programming

Calculating the norm

We can review the basic concepts illustrated in this section by calculating the norm of a set of coordinates. For a two-dimensional vector, the norm is defined as follows:

    norm = sqrt(x**2 + y**2) 

Given an array of 10 coordinates (x, y), we want to find the norm of each coordinate. We can calculate the norm by taking these steps:

  1. Square the coordinates, obtaining an array that contains (x**2, y**2) elements.
  2. Sum those with numpy.sum over the last axis.
  3. Take the square root, element-wise, with numpy.sqrt.

The final expression can be compressed in a single line:

    r_i = np.random.rand(10, 2)     norm = np.sqrt((r_i ** 2).sum(axis=1))     print(norm)    # Output:    # [ 0.7314  0.9050  0.5063  0.2553  0.0778   0.9143   1.3245   0.9486 1.010 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Programming - Second Edition

Advanced Python Programming - Second Edition

Quan Nguyen
Expert Python Programming - Third Edition

Expert Python Programming - Third Edition

Michał Jaworski, Tarek Ziadé, Cody Jackson
Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781838551216Supplemental Content