python 2.6 文档状态x % y
定义为 x / y 的余数(http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex)。我不清楚到底发生了什么,因为:
for i in range(2, 11):
print 1.0 % i
打印“1.0”十次,而不是我预期的“0.5、0.333333、0.25”等(1/2 = 0.5 等)。
python 2.6 文档状态x % y
定义为 x / y 的余数(http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex)。我不清楚到底发生了什么,因为:
for i in range(2, 11):
print 1.0 % i
打印“1.0”十次,而不是我预期的“0.5、0.333333、0.25”等(1/2 = 0.5 等)。
取模是在整数上下文中执行的,而不是小数(余数是整数)。所以:
1 % 1 = 0 (1 times 1 plus 0)
1 % 2 = 1 (2 times 0 plus 1)
1 % 3 = 1 (3 times 0 plus 1)
6 % 3 = 0 (3 times 2 plus 0)
7 % 3 = 1 (3 times 2 plus 1)
8 % 3 = 2 (3 times 2 plus 2)
etc
如何获得 x / y 的实际余数?
我认为您的意思是进行常规浮点除法?
for i in range(2, 11):
print 1.0 / i
我认为您可以通过执行以下操作获得所需的结果:
for i in range(2, 11):
print 1.0*(1 % i) / i
如其他人所解释的,这将计算(整数)余数。然后再除以分母,得到商的小数部分。
请注意,我将模运算的结果乘以 1.0 以确保完成浮点除法运算(而不是整数除法,这将导致 0)。
将 1 除以一个大于它的数字会不会导致 0 余数为 1?
人群中的数论家可能会纠正我,但我认为模数/余数仅在整数上定义。
We can have 2 types of division, that we can define through the return types:
Float: a/b. For example: 3/2=1.5
def division(a,b):
return a/b
Int: a//b and a%b. For example: 3//2=1 and 3%2=1
def quotient(a,b):
return a//b
def remainder(a,b):
return a%b