英文:
Wrong statement for dividing float number by another float number
问题
我有一个浮点数,它在逻辑上可以被另一个浮点数整除;但是Python给我返回了false的结果!?
我尝试了其他情况,其中我将浮点数除以其他浮点数,我注意到只有当分母的十分位小数是0或5时才有效!?所以有没有办法修复这个问题并得到一个True的结果?
56.00 % 11.20 == 0
结果:
false
英文:
I've a float number which is logically divisible by another float number; but Python gives me false statement for that!?
I tried other cases where I divided float numbers by other float numbers, and I noticed that works only when the tenths decimal for denominators are 0 or 5!?...so is there a way to fix this issue and get a True statement?
56.00 % 11.20 == 0
Result:
false
答案1
得分: 1
首先,你不是在进行普通的除法。你在进行的是所谓的模除运算。
其次,正如@harold在评论中建议的,计算机中,11.2 可能不等于 11.199999999999999999999999999;它们可以被视为不同的数字(查看此链接以查看 11.2 在二进制格式中的最准确表示)。正如你可以看到的 11.1999999999999992894572642399
(11.2 的二进制表示)不等于 11.199999999999999999999999999
(它们在第 14 位不同)。
你可以尝试使用 round() 来强制它保留有限的小数位数并进行比较。
尝试这样做:
round(56.00 % 11.20, 2) == 0.0
这应该返回 True。
英文:
First of all, you're not doing a normal division. You're doing what's called a modulus division.
Second of all, as suggested in the comment by @harold, in computers, 11.2 might not be equal to 11.199999999999999999999999999; they can be seen as different numbers (check this link to see the most accurate representation of 11.2 in binary format). As you can see 11.1999999999999992894572642399
(the binary representation for 11.2) is not equal to 11.199999999999999999999999999
(they differ in the 14th place)
You could try doing round() to force it to have a finite number of decimals and check against that.
Try this:
round(56.00 % 11.20, 2) == 0.0
That should give True.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论