对于整数x,经过几次迭代,x % (10 ** 9 + 7)
和x % (1e9 + 7)
给出了不同的结果。为了重现这个结果,我将分享我的LeetCode #576。超越边界路径解决方案。如果我将return ans % (10 ** 9 + 7)
更改为return ans % (1e9 + 7)
,我的解决方案将不会通过94个测试用例中的5个(意识到这需要一个小时)。
请注意,这个解决方案要比某个天才人物这里提出的一条线长得多。但是,如果我们将% (10 ** 9 + 7)
改为% (1e9 + 7)
,那么他的解决方案也会出现同样的问题。
我使用python编译器,并注意到1e9给出了浮点文字。因此,在我看来,这一特性是由浮点运算的“怪诞”引起的。但我还是不明白小数点后的零怎么会引起差异。为何会出现这种差异呢?
如果没有复制,可以在这里找到差异:https://www.diffchecker.com/PyKQCElB
为了繁衍后代,我的解决方案是:
class Solution:
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
if maxMove == 0:
return 0
current_state = [[0 for _ in range(n)] for _ in range(m)]
next_state = [[0 for _ in range(n)] for _ in range(m)]
current_state[startRow][startColumn] = 1
ans = self.count_ways(m, n, current_state)
k = 1
while k < maxMove:
# print("CS:", current_state)
for i in range(m):
for j in range(n):
next_state[i][j] = 0
if i != 0:
next_state[i][j] += current_state[i-1][j]
if i!= m-1:
next_state[i][j] += current_state[i+1][j]
if j != 0:
next_state[i][j] += current_state[i][j-1]
if j != n-1:
next_state[i][j] += current_state[i][j+1]
current_state, next_state = next_state, current_state
ans += self.count_ways(m, n, current_state)
# print("NS:", current_state)
# print("k:{},ans:{}".format(k, int(ans % 10 ** 9 + 7)))
# print("k:{},ans:{}".format(k, int(ans % 1e9 + 7)))
k += 1
# return ans % (1e9 + 7) # This is giving incorrect results.
return ans % (10 ** 9 + 7) # This works fine.
def count_ways(self, m, n, grid):
ways = 0
for i in range(m):
for j in [0, n-1]: # Checking left and right strips of a grid.
ways += grid[i][j]
for j in range(n):
for i in [0, m-1]: # Checking top and bottom strips of a grid.
ways += grid[i][j]
# This will automatically add corner boxes twice.
return ways
编辑:使用此测试用例( findPaths
的参数按顺序排列):
36
5
50
15
3
发布于 2021-05-07 16:56:04
但我还是不明白小数点后的零怎么会引起差异。
小数点不重要的地方。它在漂浮!
为何会出现这种差异呢?
因为Python中的浮点数是通常的硬件数字,这意味着它们的存储和精度有限:
>>> int(123123123123123123123.0)
123123123123123126272
# ^^^^ different!
但是Python中的整数具有无限的存储和精度("bignum"):
>>> int(123123123123123123123)
123123123123123123123
所以:
>>> 123123123123123123123 % 10**9
123123123
>>> 123123123123123123123 % 1e9
123126272.0
在第二种情况下,双方都转换为浮点,因为其中之一是。
https://stackoverflow.com/questions/67438654
复制相似问题