Python fabs() function


In today’s post, we’ll talk about the built-in fabs() function in Python. We’ll also discuss the differences between the fabs() and abs() functions.

For our practice question, we’ll write a function that accepts a list and returns a new list containing absolute values of all the numbers in the original list. Any complex numbers or non-numerical values are ignored.

Here are some topics we’ll cover in today’s post:

  • What does the fabs() function do?
  • What are the differences between the fabs() and abs() functions
  • What are complex numbers
  • How to create a complex number in Python
  • How to use a pass statement

Key Concepts

What is the fabs() function in Python

The fabs() function is a built-in function in the Python math module.

It accepts a number and returns the absolute value of that number as a FLOAT. The absolute value of a number refers to the value of the number without its sign.

If we pass an invalid input to the fabs() function (e.g. if the input is a string), the function throws an exception.

Let’s look at some examples:

import math

print(math.fabs(5))
print(math.fabs(4.3))
print(math.fabs(-1))
print(math.fabs(-2.5))
print(math.fabs('a'))

Here, we first import the math module on line 1. Next, we call the fabs() function five times, passing the values 5, 4.3, -1, -2.5 and ‘a’ as arguments to the function.

If you run the code above, you’ll get the following output:

5.0
4.3
1.0
2.5
Traceback (most recent call last):
  File "...", ..., in <module>
    print(math.fabs('a'))
TypeError: must be real number, not str

When the argument is a positive number (the first two examples), the fabs() function returns the argument as a floating-point number (even if the argument is an integer).

When the argument is negative (the third and fourth examples), it returns the absolute value (i.e. without the negative sign) of the argument as a floating-point number.

Finally, when the argument is not a numerical value (the last example), the fabs() function gives us a TypeError exception.

The abs() function in Python

Next, let’s talk about the abs() function in Python.

This function is very similar to the fabs() function; it accepts an input and returns the absolute value of the input.

However, unlike the fabs() function, the abs() function is always available and is not in the math module. Hence, we do not need to import any module to use the function.

Let’s look at some examples:

print(abs(5))
print(abs(4.3))
print(abs(-1))
print(abs(-2.5))
print(abs('a'))

In the code above, we call the abs() function five times, passing the values 5, 4.3, -1, -2.5 and ‘a’ as arguments. If you run the code above, you’ll get the following output:

5
4.3
1
2.5
Traceback (most recent call last):
  File "...", ..., in <module>
    print(abs('a'))
TypeError: bad operand type for abs(): 'str'

The key differences between the fabs() and abs() functions in Python

As you can see from the previous two sections, the abs() is very similar to the fabs() function. Both accept an input and returns the absolute value of the input. If the input is invalid, both functions throw a TypeError exception.

While the abs() and fabs() functions are indeed very similar, there are some key differences between them. Specifically,

  • the fabs() function always returns a floating-point number while the abs() function returns either an integer or a float depending on the input
  • the fabs() function throws an exception if the input is a complex number while the abs() function gives the magnitude of the number

Return Types of the two functions

The first difference is the return types of the two functions. As mentioned above, the fabs() function always return a floating-point number. In contrast, the abs() function returns an integer if the input is an integer, and a floating-point number if the input is a floating-point number.

For instance, in our previous examples, we can see that when we pass the numbers 5 and -1 to the abs() function, we get 5 and 1 as the output. In contrast, when we pass the numbers to the fabs() function, we get 5.0 and 1.0 as the output.

Complex Numbers

The second difference is in how the two functions handle complex numbers.

What are complex numbers?

Complex numbers are numbers that have an imaginary component. If you recall what you learned in your high school math, you’ll probably remember that we cannot take the square root of a negative number. For instance, we are told that square root -5 is an error. This rule is only applicable to numbers known as real numbers.

There is a special type of numbers known as complex numbers that allow us to take square roots of negative numbers.

Let’s look at an example.

3 + 4j is a complex number made up of 3 (a real number) and 4j (an imaginary number).

j stands for square root -1 (Some textbooks may use i, instead of j, to represent square root -1).

4j refers to 4 multiplied by the square root of -1.

Together, the sum of 3 and 4j gives us the complex number 3 + 4j.

If you are not familiar with complex numbers, you may think that this is a very redundant concept. Contrary to that, complex numbers are actually very useful in Mathematics and have a lot of applications in areas like trigonometry and geometry. A full discussion of complex numbers is beyond the scope of this post. If you are interested, you can check out the following site: https://brilliant.org/wiki/complex-numbers/.

For today’s practice question, we only need to know that the fabs() and abs() functions treat complex numbers very differently.

If we pass a complex number to the fabs() function, we get an error. In contrast, if we pass it to the abs() function, we get what is known as the magnitude of the number, given by the formula below:

How to create complex numbers in Python?

To create a complex number in Python, you can use kj or kJ to represent the imaginary component, where k is a constant and j (or J) stands for square root -1.

For instance, 2 + 3j and 5 - 9J are both complex numbers.

Alternatively, we can use the built-in complex() function. This function accepts two arguments – the real number component of a complex number, and the constant for the imaginary component.

For instance, to create the complex number 2 + 3j, we write complex(2, 3).

Now, let’s see how the abs() and fabs() functions differ in how they handle complex numbers.

import math
print(abs(3+4j))
print(math.fabs(3+4j))

Here, we first import the math module on line 1. Next, we pass the complex number 3+4j to the abs() and fabs() functions on lines 2 and 3 respectively.

If you run the code above, you’ll get the following output:

5.0
Traceback (most recent call last):
  File "...", ..., in <module>
    print(math.fabs(3+4j))
TypeError: can't convert complex to float

While the abs() function gives us 5.0 as the output, the fabs() function gives us an error.

Got it? Great!

Practice Question

Today’s practice question requires us to write a function called myFabs() that accepts a list and returns a new list containing the absolute values of all the numbers in the original list.

Any complex number or non-numerical values in the original list is not included in the new list.

Expected Results

To test your function, you can run the statement below:

print(myFabs([2, -3, 5, 3 + 2j, -1.2, 'A', 7 - 5j]))

You should get the following output:

[2.0, 3.0, 5.0, 1.2]

The elements 3 + 2j, 'A' and 7 - 5j are not included in the resulting list.

Additional Notes

The fabs() function throws an exception when we pass a complex number or a non-numerical value to the function. To deal with the exception, you can use the try-except statement.

Suggested Solution

The suggested solution for today’s practice question is:

Click to see the suggested solution
import math

def myFabs(myList):
    result = []
    for i in myList:
        try:
            result.append(math.fabs(i))
        except:
            pass

    return result

In the code above, we first import the math module on line 1.

Next, we define a function called myFabs() that has one parameter – myList.

Inside the function, we first declare a variable called result and assign an empty list to it.

Next, we use a for loop to loop through myList. Inside the for loop, we use a try-except statement.

Inside the try block, we try to pass i as an argument to the fabs() function. If all goes well, we append the answer returned by the fabs() function to result.

On the other hand, if the fabs() function throws an exception, we handle it in the except block.

The except block only has one statement – the pass statement. This statement tells Python to do nothing in the except block.

In Python, a try block must come with an except block. If we have a try block without an except block, Python gives us a syntax error and the code will not run.

Most of the time, when the task in the try block fails, we want to do something in the except block (for instance, we may want to print an error statement).

However, in our myFabs() function, we do not want to do anything when the fabs() function fails in the try block.

Hence, we simply use the pass statement to fulfill Python’s need for an except block, without actually doing anything inside the block.

After we finish looping through all the elements in the list, we return the result list on line 11.

With that, our function is complete.

Written by Jamie | Last Updated September 22, 2020

Recent Posts