Skip to content

[Edit]: Python abs() #7198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 146 additions & 21 deletions content/python/concepts/built-in-functions/terms/abs/abs.md
Original file line number Diff line number Diff line change
@@ -1,56 +1,181 @@
---
Title: 'abs()'
Description: 'Returns the absolute value of a numeric argument.'
Description: 'Returns the absolute value of a number.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Functions'
- 'Methods'
- 'Strings'
- 'Math'
- 'Numbers'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
- 'paths/computer-science'
---

The **`abs()`** function returns the absolute value of a numeric argument.
The **`abs()`** function is a built-in Python function that returns the absolute value of a number. The absolute value represents the distance of a number from zero on the number line, always resulting in a non-negative value. This function removes the negative sign from negative numbers while leaving positive numbers unchanged.

The `abs()` function is commonly used in mathematical calculations, data analysis, distance calculations, and anywhere there is a need to work with magnitudes rather than signed values. It accepts integers, floating-point numbers, and complex numbers as input, making it versatile for various numerical operations.

## Syntax

```pseudo
abs(n)
abs(number)
```

Return value is the absolute value of the `n` parameter, which is of type `int` or `float`.
**Parameters:**

- `number`: The numeric value for which the absolute value is to be found. This can be an integer, floating-point number, or complex number.

**Return value:**

The absolute value of `n` will be its distance from zero regardless of its direction (i.e., whether it is positive or negative). Since the absolute value is never negative, a positive value will remain unchanged and a negative value will have its negative sign removed.
The `abs()` function returns the absolute value of the given number:

## Example
- For integers and floating-point numbers: returns the positive magnitude
- For complex numbers: returns the magnitude (distance from origin)

In the example below, the absolute values of two variables, `positive` and `negative`, are returned with the `abs()` function:
## Example 1: Basic Absolute Value

This example demonstrates the basic usage of the `abs()` function with positive and negative integers and floating-point numbers:

```py
positive = 10
negative = -3.5
# Working with negative integer
negative_int = -15
print(f"Absolute value of {negative_int} is: {abs(negative_int)}")

# Working with positive integer
positive_int = 25
print(f"Absolute value of {positive_int} is: {abs(positive_int)}")

# Working with negative float
negative_float = -12.7
print(f"Absolute value of {negative_float} is: {abs(negative_float)}")

# Working with positive float
positive_float = 8.3
print(f"Absolute value of {positive_float} is: {abs(positive_float)}")
```

The output of this code is:

print(abs(positive))
```shell
Absolute value of -15 is: 15
Absolute value of 25 is: 25
Absolute value of -12.7 is: 12.7
Absolute value of 8.3 is: 8.3
```

## Example 2: Temperature Difference Calculator

print(abs(negative))
This example shows a real-world scenario where `abs()` is used to calculate the absolute difference between two temperatures, regardless of which temperature is higher:

```py
def calculate_temperature_difference(temp1, temp2):
"""Calculate the absolute difference between two temperatures"""
# Use abs() to get positive difference regardless of order
difference = abs(temp1 - temp2)
return difference

# Morning and evening temperatures
morning_temp = 18.5 # Celsius
evening_temp = 12.3 # Celsius

# Calculate difference using abs()
temp_diff = calculate_temperature_difference(morning_temp, evening_temp)

print(f"Morning temperature: {morning_temp}°C")
print(f"Evening temperature: {evening_temp}°C")
print(f"Temperature difference: {temp_diff}°C")

# Works regardless of which temperature is higher
night_temp = 8.1
day_temp = 24.7

temp_diff2 = calculate_temperature_difference(night_temp, day_temp)
print(f"\nNight temperature: {night_temp}°C")
print(f"Day temperature: {day_temp}°C")
print(f"Temperature difference: {temp_diff2}°C")
```

This will produce the following output:
The output generated by this code is:

```shell
10
3.5
Morning temperature: 18.5°C
Evening temperature: 12.3°C
Temperature difference: 6.2°C

Night temperature: 8.1°C
Day temperature: 24.7°C
Temperature difference: 16.6°C
```

## Codebyte Example
## Codebyte Example: Distance Calculation with Complex Numbers

The following example returns the absolute value from each element in the `numbers` list:
This example demonstrates using `abs()` with complex numbers to calculate distances in a 2D coordinate system, useful in physics and engineering applications:

```codebyte/python
numbers = [-19.2, 27.3, 48, -115, 302.7, -421, -2011]
import math

def calculate_distance_from_origin(x, y):
"""Calculate distance from origin using complex numbers and abs()"""
# Create complex number representing coordinate
coordinate = complex(x, y)

# abs() of complex number gives distance from origin
distance = abs(coordinate)
return distance

def calculate_distance_between_points(x1, y1, x2, y2):
"""Calculate distance between two points using complex numbers"""
# Create complex numbers for both points
point1 = complex(x1, y1)
point2 = complex(x2, y2)

print([abs(number) for number in numbers])
# Distance is abs() of the difference
distance = abs(point1 - point2)
return distance

# Calculate distance from origin
point_x = 3
point_y = 4
origin_distance = calculate_distance_from_origin(point_x, point_y)

print(f"Point coordinates: ({point_x}, {point_y})")
print(f"Distance from origin: {origin_distance}")

# Calculate distance between two points
x1, y1 = 1, 2
x2, y2 = 4, 6

point_distance = calculate_distance_between_points(x1, y1, x2, y2)

print(f"\nPoint 1: ({x1}, {y1})")
print(f"Point 2: ({x2}, {y2})")
print(f"Distance between points: {point_distance}")

# Verify with manual calculation
manual_distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(f"Manual calculation verification: {manual_distance}")
```

## Frequently Asked Questions

### 1. Can `abs()` work with complex numbers?

Yes, `abs()` returns the magnitude (modulus) of complex numbers, which is the distance from the origin in the complex plane.

### 2. What happens if I pass a string to `abs()`?

`abs()` will raise a `TypeError` because it only works with numeric types (int, float, complex).

### 3. What is the difference between `abs()` and `math.fabs()`?

`abs()` works with integers, floats, and complex numbers, while `math.fabs()` only works with floats and always returns a float.

### 4. Can `abs()` be used with decimal numbers?

Yes, `abs()` works with Python's `decimal.Decimal` objects as they implement the required numeric protocols.

### 5. What is the time complexity of `abs()`?

`abs()` has O(1) time complexity for integers and floats, making it very efficient for mathematical operations.