What is the numpy.fabs() function in NumPy?

Overview

The absolute() function in NumPy computes the absolute values of all the elements of an array.

The absolute value of a number is the magnitude, or the distance, between the number and zero. It is always a positive number.

Syntax

numpy.fabs(x, /, out=None, *, where=True)
Syntax for the fabs() function in NumPy

Parameter value

The fabs() function takes the following parameter values:

  • x: This represents an input array of values. It is a required parameter.
  • out: This represents the location where the result is stored. It is an optional parameter.
  • where : This represents the condition over which the input is being broadcast. At a given location where this condition is True, the resulting array is set to the ufunc result. Otherwise, the resulting array retains its original value. This is an optional parameter.
  • **kwargs: This represents other keyword arguments. It is an optional parameter.

Return value

The fabs() function returns an array of the same shape as the input array passed to it. This array holds the absolute values of the elements of the input array.

Code example

import numpy as np
# Creating an input array of complex values
x = np.array([-1, 6, -2.5, 2])
# Implementing the fabs() function
myarray = np.fabs(x)
print(x)
print(myarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array x  using the array() function.
  • Line 7: We implement the fabs() function on the input array. We assign the result to a variable myarray.
  • Line 9: We print the variable x.
  • Line 10: We print the variable myarray.

Free Resources