当我处理一些大数字时,比如,
取任意随机数 3289568273632879456235 。
我发现在 Chrome 或 Firefox console
3289568273632879456235 % 6 = 0
但是在 Python shell
3289568273632879456235 % 6 = 5。
之后我发现 Python 的回答是正确的。
所以我不明白为什么会有不同的答案。
谁能给我解释一下。
请您参考如下方法:
这是因为 javascript 没有整数的概念——只有数字(存储为 IEEE float )。 float 具有有限的精度,如果您尝试使数字比 float 所能表示的更精确,它将被“chop ”——这正是您的大数字所发生的情况。考虑 python“等效”:
>>> int(float(3289568273632879456235)) % 6
0L
这里有一些更有趣的花絮,希望能使这一点更清楚:
>>> int(float(3289568273632879456235)) # Notice, the different result due to loss of precision.
3289568273632879706112L
>>> int(float(3289568273632879456235)) == int(float(3289568273632879456236)) # different numbers, same result due to "truncation"
True
