将浮点数除以另一个浮点数的错误语句

huangapple go评论62阅读模式
英文:

Wrong statement for dividing float number by another float number

问题

我有一个浮点数,它在逻辑上可以被另一个浮点数整除;但是Python给我返回了false的结果!?

我尝试了其他情况,其中我将浮点数除以其他浮点数,我注意到只有当分母的十分位小数是05时才有效!?所以有没有办法修复这个问题并得到一个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.

huangapple
  • 本文由 发表于 2023年6月26日 17:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定