Mastering NumPy: Part 3 (Mathematical Operations)

Nandeda Narayan
7 min readMay 24, 2023

--

This is the 4th blog post in our comprehensive series (Access all posts of this series here) on NumPy!

Note: Don’t forget to bookmark the full 50 examples series — Mastering NumPy: A 5 Parts Series to Master Numpy

Introduction

NumPy is renowned for its exceptional mathematical capabilities, making it a go-to library for numerical computations. From performing basic arithmetic operations to advanced mathematical functions, NumPy provides an extensive range of tools to crunch numbers efficiently. In this blog post, we will delve into 10 practical examples of mathematical operations using NumPy, demonstrating its prowess in numerical computing.

1. Performing element-wise addition, subtraction, multiplication, and division on arrays

import numpy as np

# Creating two NumPy arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8, 9, 10])

# Element-wise addition
addition_result = arr1 + arr2
print("Addition Result:")
print(addition_result)

# Element-wise subtraction
subtraction_result = arr1 - arr2
print("Subtraction Result:")
print(subtraction_result)

# Element-wise multiplication
multiplication_result = arr1 * arr2
print("Multiplication Result:")
print(multiplication_result)

# Element-wise division
division_result = arr1 / arr2
print("Division Result:")
print(division_result)

# Output
#Addition Result:
#[ 7 9 11 13 15]

#Subtraction Result:
#[-5 -5 -5 -5 -5]

#Multiplication Result:
#[ 6 14 24 36 50]

#Division Result:
#[0.16666667 0.28571429 0.375 0.44444444 0.5 ]

In the above code, we create two NumPy arrays arr1 and arr2. Then, we perform element-wise addition, subtraction, multiplication, and division using the corresponding operators +, -, *, and /.

2. Computing the sum, mean, and standard deviation of an array

Here’s an example of computing the sum, mean, and standard deviation of an array using the NumPy functions numpy.sum(), numpy.mean(), and numpy.std()

import numpy as np

# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Computing the sum
sum_result = np.sum(arr)
print("Sum:", sum_result)

# Computing the mean
mean_result = np.mean(arr)
print("Mean:", mean_result)

# Computing the standard deviation
std_result = np.std(arr)
print("Standard Deviation:", std_result)

In the above code, we create a NumPy array arr. Then, we use numpy.sum() to compute the sum of all elements in the array, numpy.mean() to compute the mean value of the array, and numpy.std() to compute the standard deviation of the array.

3. Finding the minimum and maximum values in an array

Here’s an example of finding the minimum and maximum values in an array using the NumPy functions numpy.min() and numpy.max():

import numpy as np

# Creating a NumPy array
arr = np.array([5, 3, 8, 2, 7])

# Finding the minimum value
min_value = np.min(arr)
print("Minimum value:", min_value)

# Finding the maximum value
max_value = np.max(arr)
print("Maximum value:", max_value)

Output:

Minimum value: 2
Maximum value: 8

In the above code, we create a NumPy array arr. Then, we use numpy.min() to find the minimum value in the array and numpy.max() to find the maximum value.

4. Computing the dot product of two arrays

The dot product of two matrices is a mathematical operation that combines the corresponding elements of the matrices to produce a scalar value.

In NumPy, the numpy.dot() function can be used to compute the dot product of two arrays by performing element-wise multiplication and summing the results.

import numpy as np

# Creating two NumPy arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Computing the dot product
dot_product = np.dot(arr1, arr2)
print("Dot product:", dot_product)

# Dot product: 32

In the above code, we create two NumPy arrays arr1 and arr2. Then, we use numpy.dot() to compute the dot product between the two arrays. The dot product is the sum of the element-wise multiplication of the corresponding elements in the arrays.

5. Applying trigonometric functions (e.g., sine, cosine) to an array

Here’s an example of applying trigonometric functions (sine and cosine) to an array using the NumPy functions numpy.sin() and numpy.cos()

import numpy as np

# Creating a NumPy array
arr = np.array([0, np.pi/2, np.pi])

# Applying sine function
sin_result = np.sin(arr)
print("Sine:", sin_result)

# Applying cosine function
cos_result = np.cos(arr)
print("Cosine:", cos_result)

# Sine: [0.0000000e+00 1.0000000e+00 1.2246468e-16]
# Cosine: [ 1.000000e+00 6.123234e-17 -1.000000e+00]

In the above code, we create a NumPy array arr that contains three angles: 0, π/2 (90 degrees), and π (180 degrees). We then use numpy.sin() to apply the sine function to each element of the array, and numpy.cos() to apply the cosine function.

6. Calculating the exponential and logarithmic values of an array

You can use the NumPy library in Python to calculate the exponential and logarithmic values of an array using the numpy.exp() and numpy.log() functions, respectively. Here's an example:

import numpy as np

# Create an array
arr = np.array([1, 2, 3, 4, 5])

# Calculate the exponential values
exp_arr = np.exp(arr)
print("Exponential values:", exp_arr)

# Calculate the logarithmic values
log_arr = np.log(arr)
print("Logarithmic values:", log_arr)

# Exponential values: [ 2.71828183 7.3890561 20.08553692 54.59815003 148.4131591 ]
# Logarithmic values: [0. 0.69314718 1.09861229 1.38629436 1.60943791]

In the code above, we calculate the exponential values using np.exp(arr) and store the result in the exp_arr variable. Similarly, we calculate the logarithmic values using np.log(arr)

7. Applying element-wise comparisons between arrays using logical operators

You can use logical operators such as numpy.logical_and() and numpy.logical_or() to apply element-wise comparisons between arrays in NumPy. These functions perform element-wise logical operations on two or more arrays and return a new array with the resulting Boolean values. Here's an example:

import numpy as np

# Create two arrays
arr1 = np.array([True, True, False, False])
arr2 = np.array([True, False, True, False])

# Element-wise logical AND
result_and = np.logical_and(arr1, arr2)
print("Element-wise logical AND:", result_and)

# Element-wise logical OR
result_or = np.logical_or(arr1, arr2)
print("Element-wise logical OR:", result_or)

# Element-wise logical AND: [ True False False False]
# Element-wise logical OR: [ True True True False]

In the code above, we import NumPy as np and create two Boolean arrays arr1 and arr2 with values [True, True, False, False] and [True, False, True, False], respectively. We then apply the element-wise logical AND operation using np.logical_and(arr1, arr2) and store the result in the result_and variable. Similarly, we apply the element-wise logical OR operation using np.logical_or(arr1, arr2)

8. Performing element-wise rounding of an array using numpy.round().

You can use the numpy.round() function in NumPy to perform element-wise rounding of an array. This function rounds each element of the array to the nearest integer or to the specified number of decimals. Here's an example:

import numpy as np

# Create an array
arr = np.array([1.4, 2.7, 3.2, 4.8, 5.1])

# Perform element-wise rounding
rounded_arr = np.round(arr)
print("Rounded array:", rounded_arr)

# Rounded array: [1. 3. 3. 5. 5.]

We apply element-wise rounding using np.round(arr) and store the result in the rounded_arr variable.

By default, numpy.round() rounds to the nearest integer, but you can also specify the number of decimals to round to by providing the decimals parameter. For example, if you want to round to one decimal place, you can modify the code as follows:

rounded_arr = np.round(arr, decimals=1)

# Output - [1.4 2.7 3.2 4.8 5.1]

The elements in the rounded_arr array are rounded to one decimal place.

9. Computing the element-wise absolute values of an array

You can use the numpy.abs() function in NumPy to compute the element-wise absolute values of an array. This function returns a new array with the absolute values of each element in the original array. Here's an example:

import numpy as np

# Create an array
arr = np.array([-1, -2, 3, -4, 5])

# Compute element-wise absolute values
abs_arr = np.abs(arr)
print("Absolute values:", abs_arr)

# Absolute values: [1 2 3 4 5]

In the code above, we compute the element-wise absolute values using np.abs(arr).

The numpy.abs() function can also be used with arrays that contain complex numbers. In that case, it returns the magnitude of each complex number.

10. Finding the index of the maximum and minimum values in an array using numpy.argmax() and numpy.argmin()

You can use the numpy.argmax() and numpy.argmin() functions in NumPy to find the indices of the maximum and minimum values in an array, respectively. These functions return the indices of the maximum and minimum values along a specified axis or in the flattened array.

import numpy as np

# Create an array
arr = np.array([4, 2, 9, 1, 7])

# Find the index of the maximum value
max_index = np.argmax(arr)
print("Index of the maximum value:", max_index)

# Find the index of the minimum value
min_index = np.argmin(arr)
print("Index of the minimum value:", min_index)

# Index of the maximum value: 2
# Index of the minimum value: 3

In the code above, we use np.argmax(arr) to find the index of the maximum value in the array. Similarly, we use np.argmin(arr) to find the index of the minimum value in the array.

Note that if there are multiple occurrences of the maximum or minimum value in the array, numpy.argmax() and numpy.argmin() will return the index of the first occurrence.

Conclusion

In this blog post, we explored the wide array of mathematical operations offered by NumPy. We covered basic arithmetic operations, statistical calculations, trigonometric functions, and more. NumPy’s mathematical prowess empowers data scientists to perform complex calculations with ease, paving the way for in-depth analysis and modeling.

Next Blog Post

In the next blog post Mastering NumPy: Part 4(Array Broadcasting) , we will uncover the concept of array broadcasting in NumPy. We will explore how broadcasting simplifies element-wise operations between arrays of different shapes, enhancing code readability and computational efficiency.

Note: Don’t forget to bookmark the full 50 Numpy examples series — Mastering NumPy: A 5 Parts Series to Master Numpy

--

--