我从基数排序中看到了这个代码示例:
def getDigit(num, base, digit_num):
# pulls the selected digit
return (num // base ** digit_num) % base
Run Code Online (Sandbox Code Playgroud)
什么是" //"在Python呢?
我偶然发现了np.float32或np.float64的分区结果,我不明白
我在Python 3.6.7中使用numpy 1.15.4
>>> import numpy as np
>>> np.float32(0)//1
-0.0
Run Code Online (Sandbox Code Playgroud)
我知道,我可以通过abs()等解决方法,但为什么我首先得到"-0.0"而不是"0.0"?
我遇到了代码语法d //= 2,其中d是一个变量.这不是任何循环的一部分,我不太明白.
有人可以开导我吗?
python python-2.x integer-division python-3.x floor-division
我试图在hackerrank中解决这个问题.在某些时候,我必须检查数字是否除以n(给定输入).
除了一个测试用例(不是问题)之外,这段代码非常有效:
if __name__ == '__main__':
tc = int(input().strip())
for i_tc in range(tc):
n = int(input().strip())
while n % 2 == 0 and n is not 0:
n >>= 1
last = 0
for i in range(3, int(n ** 0.5), 2):
while n % i == 0 and n > 0:
last = n
n = n // i # Concentrate here
print(n if n > 2 else last)
Run Code Online (Sandbox Code Playgroud)
现在你可以看到我只在i是n的因子时除以数字.例如,如果数字是i = 2且n = 4那么n/2和n // 2没有任何区别.
但是当我使用下面的代码时,所有测试用例都会失败:
if …Run Code Online (Sandbox Code Playgroud) >>> print (12//0.2)
59.0
>>> print(floor(12/0.2))
60
Run Code Online (Sandbox Code Playgroud)
在这种情况下,为什么楼层划分不按规则工作?
PS这里Python是治疗0.2如0.20000000001在floor division这样的情况下
(12/0.2000000001)被产生59.999999...
并floor(59.999999999)输出59
但是不知道为什么Python是治疗0.2如0.2000000001在floor division情况下,但不是在division如此吗?
在 C 中可以进行楼层划分,例如:
int floor_div(int a, int b) {
int d = a / b;
if (a < 0 != b < 0) { /* negative output (check inputs since 'd' isn't floored) */
if (d * a != b) { /* avoid modulo, use multiply instead */
d -= 1; /* floor */
}
}
return d;
}
Run Code Online (Sandbox Code Playgroud)
但这似乎可以简化。
在 C 中有没有更有效的方法来做到这一点?
请注意,这几乎与这个问题相反:C/C++ 中整数除法的快速上限
我知道在python中,您可以像这样进行楼层分割:
5 // 2 #2
Run Code Online (Sandbox Code Playgroud)
//用于Java中完全不同的东西。有什么办法可以在java中进行楼层分割?
我是Python 3.6.0的新用户.我试图划分2个产生大量输出的数字.但是,使用
return ans1 // ans2
Run Code Online (Sandbox Code Playgroud)
使用时产生55347740058143507128
return int(ans1 / ans2)
Run Code Online (Sandbox Code Playgroud)
生产55347740058143506432.
哪个更准确,为什么会这样?
有人可以解释一下语义吗
n % 2 == 1
Run Code Online (Sandbox Code Playgroud)
和
n //= 2
Run Code Online (Sandbox Code Playgroud)
据我了解,检查byn % 2 == 1除法的余数是否为。n21
关于什么n //= 2?这是楼层划分吗?但什么?n除以2?
在 Python 5//2 中是楼层划分。
在朱莉娅:
5//2
退货
5//2
我如何在 Julia 中进行楼层划分?
如果我理解正确的话,下限除法的返回值始终是整数,即使被除数和/或除数不是整数,那么为什么它不总是返回整数。
在我的例子中这是有害的,因为从大浮点数转换为 int 而不是将返回值作为任意精度整数显然会损失精度。
我看不到任何执行浮点除法以返回整数的函数。显然我可以创建一个函数来执行此操作,例如将两个值乘以相同的数量,以便它们都是整数,但它会比 C 实现慢很多。
这是一个例子:5.2 // 2不是2.0。2
python floating-point precision arbitrary-precision floor-division