python divmod
Python divmod() function is used to perform division on two input numbers. The numbers should be non-complex and can be written in any format such as decimal, binary, hexadecimal etc.
Python divmod()函数用于对两个输入数字进行除法。 数字应该是非复杂的,并且可以以任何格式编写,例如十进制,二进制,十六进制等。
Python divmod()
syntax is:
Python divmod()
语法为:
divmod(a, b)
The output is a tuple consisting of their quotient and remainder when using integer division.
使用整数除法时,输出是一个由它们的商和余数组成的元组 。
For integer arguments, the result is the same as (a // b, a % b).
对于整数参数,结果与(a // b,a%b)相同。
For floating point numbers the result is (q, a % b), where q is usually (math.floor(a / b), a % b). In any case q * b + a % b is very close to a.
对于浮点数,结果为(q,a%b),其中q通常为(math.floor(a / b),a%b)。 无论如何,q * b + a%b非常接近a。
If a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
如果%b不为零,则它的符号与b相同,并且0 <= abs(a%b)<abs(b)。
# simple example, returns (a // b, a % b) for integers
dm = divmod(10, 3)
print(dm)
x, y = divmod(10, 3)
print(x)
print(y)
dm = divmod(0xF, 0xF) # hexadecimal
print(dm)
Output:
输出:
(3, 1)
3
1
(1, 0)
# floats, returns usually (math.floor(a / b), a % b)
dm = divmod(10.3, 3)
print(dm)
dm = divmod(11.51, 3)
print(dm)
dm = divmod(-11.51, 3)
print(dm)
Output:
输出:
(3.0, 1.3000000000000007)
(3.0, 2.51)
(-4.0, 0.4900000000000002)
Notice that in case of floating points, the q * b + a % b
is very close to a
in some cases.
注意,在浮点情况下, q * b + a % b
在某些情况下非常接近a
。
If we pass complex numbers as argument, we will get TypeError
.
如果我们将复数作为参数传递,则会得到TypeError
。
dm = divmod(3 + 2J, 3)
Output: TypeError: can't take floor or mod of complex number.
输出: TypeError: can't take floor or mod of complex number.
Reference: Official Documentation
参考: 官方文档
python divmod