The abs()
function returns the absolute value of a number, removing any negative sign.
print(abs(-10))
Output:
10
Syntax:
abs(number)
The number can be positive or negative, and abs()
returns its distance from zero, which is always a positive value.
Common Use Cases:
To calculate the difference between two points, like distance on a number line, without worrying about direction (negative or positive values).
Calculating distances:
distance = abs(x2 - x1)
Converting negative financial losses into positive values:
loss = abs(-500) # Outputs 500
Return Absolute Value of a Complex Number:
complex_num = abs(3 + 4j) # Magnitude of the complex number
print(complex_num)
Output:
5.0
Working with mathematical formulas like finding magnitude in physics or statistics.
Finding Magnitude in Physics:
force = abs(-50) # Magnitude of force is 50
Normalizing data for machine learning, where negatives may not have significance.
Normalizing Data in Machine Learning:
value = abs(-0.75) # Convert negative data to positive for consistency
Handling Temperature Differences:
temp_difference = abs(-10 - 15) # Output: 25 (absolute difference)