python 绝对值
Python abs() function returns the absolute value of the number. It’s one of the built-in functions in python builtins module.
Python abs()函数返回数字的绝对值。 它是python Builtins 模块中的内置函数之一。
使用abs()的Python绝对值 (Python Absolute Value using abs())
Python abs() takes a single argument, which has to be a number, and returns its absolute value.
Python abs()接受一个参数,该参数必须为number ,并返回其绝对值。
- Integer, Long – returns absolute value. 整数,长整数–返回绝对值。
- Float – returns absolute value. 浮点数-返回绝对值。
- Complex – returns its magnitude 复杂-返回其大小
- Numbers in different formats – returns absolute value in decimal system even if numbers are defined in binary, octal, hexadecimal or exponential form. 不同格式的数字–即使数字以二进制,八进制,十六进制或指数形式定义,也以十进制返回绝对值。
带有整数的Python abs() (Python abs() with integers)
import sys
x = 5 # int
print(abs(x))
x = sys.maxsize # long
print(abs(x))
Output:
输出:
5
9223372036854775807
Python的float绝对值 (Python absolute value of float)
x = 50.23434 # float
print(abs(x))
Output:
输出:
50.23434
带有复数的Python abs() (Python abs() with complex numbers)
x = 10 - 4j # complex
print(abs(x))
x = complex(10, 2) # another complex example
print(abs(x))
Output:
输出:
10.770329614269007
10.198039027185569
具有不同格式编号的Python abs() (Python abs() with different format numbers)
# numbers in different formats
x = 10.23e1/2 # exponential
print(abs(x))
x = 0b1010 # binary
print(abs(x))
x = 0o15 # octal
print(abs(x))
x = 0xF # hexadecimal
print(abs(x))
Output:
输出:
51.15
10
13
15
That’s all for quick examples of python absolute values of numbers using abs() function.
这就是使用abs()函数的python数值绝对值的快速示例。
GitHub Repository.
GitHub存储库中检出完整的python脚本和更多Python示例。
Reference: Official Documentation
参考: 官方文档
翻译自: https://www.journaldev.com/22608/python-absolute-value-abs
python 绝对值