In this Python lesson you will learn how to calculate absolute value using Numpy. You will get to know several useful tricks.

## Basic Absolute Value Calculation

To find the absolute value of a number, you can simply use the `np.abs`

method.

import numpy as np my_scalar = -77 my_abs_value = np.abs(my_scalar) print(f"My absolute value equals: {my_abs_value}")

For instance, the absolute value of -77 is 77.

You can also calculate the absolute values of arrays in a similar manner:

import numpy as np my_array = np.array([-1, -2]) my_abs_value = np.abs(my_array) print(f"My absolute value equals: {my_abs_value}")

For an array like (-1, -2), the absolute values become (1, 2).

Regardless of the array’s size, the calculation remains the same:

import numpy as np my_array = np.array([[-1, -2], [3, -4], [-5, 6]]) my_abs_value = np.abs(my_array) print(f"My absolute value equals: \n{my_abs_value}")

## Calculating Absolute Differences in Numpy Matrices

You can also compute the absolute difference between Numpy matrices:

import numpy as np my_first_array = [[-2, -3, 4], [-4, 5, -6]] my_second_array = [[-1, 2, 7], [-8, 9, -9]] my_first_array, my_second_array = map(np.array, (my_first_array, my_second_array)) abs_difference = np.abs(my_first_array) - np.abs(my_second_array) print(f"The absolute difference between arrays equals: \n{abs_difference}")

In this example, we’ve mapped two arrays and subtracted them using the `np.abs()`

method. You can perform various calculations on Numpy arrays or matrices in a similar fashion.

## Numpy Functions for Absolute Value

Numpy provides two functions for absolute value calculations: `np.abs()`

and `np.absolute()`

. They are functionally identical, so choose the one that suits you best. I prefer `np.abs()`

for its brevity, but the choice is yours.