What is the abs() function in python?
In Python, 'abs()'
is a built-in function that returns the absolute value of a number. The absolute value of a number is its value without regard to its sign.
example -
x = -5
y = abs(x)
print(y) # Output: 5
In the above example, we first assign the value -5 to the variable x. We then use the abs() function to get the absolute value of x and assign it to the variable y. Finally, we print the value of y, which is 5.
Here's an example of using abs()
in Python:
Example 1: Getting the absolute value of a floating-point number
x = -3.14
y = abs(x)
print(y) # Output: 3.14
In this example, we use the abs() function to get the absolute value of the floating-point number -3.14. The result is 3.14, which is the same value without its negative sign.
Example 2: Getting the absolute value of a complex number
z = -2 + 3j
w = abs(z)
print(w) # Output: 3.605551275463989
In this example, we use the abs() function to get the absolute value of a complex number -2 + 3j. The result is 3.605551275463989, which is the magnitude of the complex number without its sign.
Example 3: Getting the absolute difference between two numbers
a = 5
b = 8
diff = abs(a - b)
print(diff) # Output: 3
In this example, we use the abs() function to get the absolute difference between two numbers a and b. The difference between 5 and 8 is -3, but the absolute value of -3 is 3, which is the final output.