Home > Article > Backend Development > Use Python's abs() function to get the absolute value of a number
Use Python's abs() function to obtain the absolute value of a value. Code example
The absolute value is the non-negative value of a value, that is, the distance from the origin. In Python, we can use the abs() function to get the absolute value of a numerical value.
abs() function accepts a value as a parameter and returns the absolute value of the value. Regardless of whether the input is a positive number, a negative number, or zero, the abs() function returns a nonnegative number.
The following are some code examples that use the abs() function to obtain absolute values:
# 示例1:获取整数的绝对值 num1 = -10 result1 = abs(num1) print("绝对值为:", result1) # 输出:绝对值为: 10 # 示例2:获取浮点数的绝对值 num2 = -3.14 result2 = abs(num2) print("绝对值为:", result2) # 输出:绝对值为: 3.14 # 示例3:获取复数的绝对值 num3 = -2 + 3j result3 = abs(num3) print("绝对值为:", result3) # 输出:绝对值为: 3.605551275463989 # 示例4:获取零的绝对值 num4 = 0 result4 = abs(num4) print("绝对值为:", result4) # 输出:绝对值为: 0
In the code examples, we pass integers, floating point numbers, complex numbers, and Zero as argument and save the returned absolute value in the variable result. Finally, we use the print() function to print out the results.
Please note that for complex numbers, the abs() function calculates the modulus of the complex number (that is, the square root of the sum of squares).
Using the abs() function can easily obtain the absolute value of a value. Regardless of whether the value is positive or negative, you can get a non-negative result. In this way, we can easily handle scenarios that require absolute values in the program, such as numerical comparisons, distance calculations, etc.
Hope this simple code example can help you understand how to use Python's abs() function to get the absolute value of a numerical value. If you have any questions or need further assistance, please feel free to ask.
The above is the detailed content of Use Python's abs() function to get the absolute value of a number. For more information, please follow other related articles on the PHP Chinese website!