NumPy Nuggets: 5 Hidden Functions for Data Wizards

Coding Cube
7 min readJun 2, 2021

NumPy is a versatile array-processing package that offers a variety of impressive mathematical functions.NumPy delivers a high-performance multidimensional array object, accompanied by a multitude of fascinating APIs. In this article, we will explore five essential NumPy functions you need to be familiar with. I’ve aimed to present everything in a simplified manner.

For more information you must visit the official site.

Functions:

1. numpy.linalg.det

2. numpy.linalg.norm

3. numpy.dot

4. numpy.angle

5. numpy.linalg.solve

Function 1 : numpy.linalg.det

This numpy function can evaluate the determinant of a square matrix. For example:

for this ‘arr’ matrix the function will return the determinant of the matrix is -306.

import numpy as npA = np.array([
[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])
det = np.linalg.det(A)
print(det)
Output:
-306

Implementation: Area of triangle.

The area of triangle whose three coordinates are given say, x(3, 3, 1), y(-3, 2, -1) and z(8, 6, 3) can be measured using the following formula:

Here, each row represents the x-y-z components of a point in a given three dimensional space.

import numpy as np# implementation 1
# find area of triangle
def find_triangular_area(pt1, pt2, pt3):
arr = np.array([pt1, pt2, pt3]) # creates a 3d array
return np.linalg.det(arr)/2
p1 = [3, 3, 1]
p2 = [-3, 2, -1]
p3 = [8, 6, 3]
area = find_triangular_area(p1, p2, p3)
print(f'area: {area:.2f}')
Output:
area: 2.50

Explanation: Here, find_triangular_area takes three points with corresponding x-y-z components in lists, enclose these lists in a parent array and thus create a 3x3 matrix representing the triangle in three dimensional space. Then it calculate its determinant. Half of the determinant is the area of the given triangle. Return.

Function 2: numpy.linalg.norm

The function calculate the modulus of a given vector or a matrix.

Essentially the norm determines the magnitude of a vector or a square matrix. There are multiple types of norms for a vector and matrix. Some common norms are: 1-norm, 2-norm or Euclidean norm, positive infinity-norm, negative infinity-norm, Frobenius norm etc. For more information of numpy linalg.norm function see here.

The type 2-norm calculate the Euclidean distance of a given vector from the origin:

The numpy linalg.norm() function takes 4 arguments. Two are most useful:

x: Take vector or matrix as input and,

ord: Defines the type of norm. In case left blank, it calculates the 2-norm for vectors and Frobenius norm for matrix.

import numpy as npa = np.array([-3, 4])
dist = np.linalg.norm(a)
print('distance from origin: ', dist)
Output:
distance from origin: 5.0

Implementation: Calculate distance between two points.

import numpy as np# Implementation 2
# distance between two points
def cal_distance(v1, v2):
v1 = np.array([v1])
v2 = np.array([v2])
diff = v1 - v2
return np.linalg.norm(diff)

dist = cal_distance([-1, 6, 6], [-4, 9, 6])
print(f'distance between v1[-1, 6, 6] and v2[-4, 9, 6] is: {dist:.2f}')
Output:
distance between v1[-1, 6, 6] and v2[-4, 9, 6] is: 4.24

Explanation:

Here, in cal_distance function, both vectors are encoated in numpy array as np.linalg.norm() function only takes numpy array as argument. Then the difference between each vector passes to the norm() to calculate the Euclidean distance. Return.

distance between two points

Function 3: numpy.dot

This function returns the dot product of two vectors. Dot product defines how much of a vector is pointing towards the another vector. If the two vectors are pointing at the same direction then the resultant would be large positive scalar and if the two vectors pointing perpendicularly then the magnitude of the resultant will be zero and quite in the opposite direction will produce negative resultant. Mathematically it can be defined as:

# calculate dot productimport numpy as npa = np.array([1, 3, 4])   # vector 1
b = np.array([4, 3, 1]) # vector 2
cp = np.dot(a, b)
print(cp)
Output:
17

Implementation: Find if two given vectors are perpendicular or not

import numpy as np# Implementation 3
# Find if two given vectors are perpendicular or not
def is_perpendicular(v1, v2):
v1 = np.array(v1)
v2 = np.array(v2)
if np.dot(v1, v2) == 0:
return True
else:
return False
dot_product = is_perpendicular([2, -3, 5], [-2, 2, 2])
print(f’v1[-1, 6, 6] and v2[-4, 9, 6] are perpendicular: {dot_product}’)

Explanation:

The is_perpendicular function, takes the components of two vectors in two numpy arrays. calculate their dot product using numpy.dot() function. If the dot product of two vector is equal to zero then it returns True as two perpendicular vectors cancel out each other effect in that direction.

Function 4: numpy.angle

This function calculate the complex argument. Complex argument is essentially the angle between Real Axis and the line joining complex point (z) in the complex plane.

Let’s, find out the maths of complex argument. Say a complex number

where x is the “real” part and y is the “imaginary” part of the complex number z. Now any complex number can be represented as exponential form:

You can find more interesting explanation of Complex argument in Here.

import numpy as npcomplx_no = 2+2j  # a complex numberangle = np.angle(complx_no, deg=True)
print(angle)
Output:
45.0

Implementation: Calculating angle between two complex numbers

import numpy as np# Implementation 4
# Evaluating angle between two complex numbers
def find_cmplx_angle(cmplx_num1, cmplx_num2):
cmplx_list = [cmplx_num1, cmplx_num2]
cmplx_angle = np.angle(cmplx_list, deg=True)
return cmplx_angle[0] - cmplx_angle[1]
cmplx_num1 = 3+1j
cmplx_num2 = 4-2j
res = find_cmplx_angle(cmplx_num1, cmplx_num2)
print(f'the angle between {cmplx_num1} and {cmplx_num2} is: {res:.2f}')

Output:
the angle betw.(3+1j) and (4-2j) is: 45.00

Explanation:

The find_cmplx_angle function, takes two complex numbers. The numbers must be encoated before passing to numpy.angle() method. The numpy.angle() method calculate the corresponding arguments of the complex numbers of the cmplx_list and return the result as numpy array to cmplx_angle . Then difference between the angle is calculated and Return.

Function 5: numpy.linalg.solve

This function does solve a linear matrix equation or system of linear equation. Consider the following system of equations, represent planes in a three dimensional space have a common point of intersection:

The equations can be rewritten as:

A general intuition is that the equations that are not parallel (considering three distinct planes in 3D or two lines in 2D space), the single point of intersection will satisfy all the equations and therefore represent the solution to the system.

The numpy.linalg.solve() function solves these equations by taking matrices out these equation which is look like following one:

You can find a good blog describing the whole process with example in here.

Implementation: Solve a linear system of equations

import numpy as np# Implementation 5
# solving linear system
"""
x + 2 y + 3z = 62
x − 3 y + 2 z = 143
x + y − z = − 2.
"""coeff1 = [1, 2, 3]
coeff2 = [1, -3, 2]
coeff3 = [1, 1, -1]
D = [62, -143, -2]
def solve_system(coeff1, coeff2, coeff3, D):
coeff_mtrx = np.array([coeff1, coeff2, coeff3])
dependent_variable = np.array(D)
return np.linalg.solve(coeff_mtrx, dependent_variable)
res = solve_system(coeff1, coeff2, coeff3, D)
print(f'x= {res[0]}, y= {res[1]}, z= {res[2]}')

Explanation:

The solve_system wrapper function, takes all three coefficient vectors of the equations and wrap it in coefficient matrix (numpy array) and also dependent variables. Pass both array to numpy.linalg.solve() method. Return.

GitHub Repo:

https://github.com/officialPrasanta/Numpy-Blog

Reference:

This article is enriched with the enormous articles and blogs of the following portals:

Thanks a lot :)

--

--

Coding Cube

Mastering Devs. Maintained by Prasanta Roy Choudhury.