[英]Modulus and float numbers
How modulus are interpreted is by saying how many times "a" can reach to "b" but not by multiplying, just by adding up.模数的解释方式是说“a”可以达到“b”的次数,而不是乘法,只是加起来。
If we were going to find the modulus of 20
from 1.3
, it will add up 1.3 + 1.3 +...+ 1.3 = 19.5
which 20-19.5
will be 0.5
.如果我们要从
1.3
中找到20
的模数,它将加起来1.3 + 1.3 +...+ 1.3 = 19.5
其中20-19.5
将是0.5
。
But if we operate the formula that everyone explains with modulus, that's by dividing and multiplying and then getting the remainder, we will not get an exact number, for example:但是如果我们用模运算大家解释的那个公式,就是除法乘法然后求余数,就得不到确切的数,比如:
6%2 = 0
and 7%2 = 1
because 6/2 = 3
times and 3*2 = 6
, that's why answer is 0 and 1, but if we use 20 % 1.3
this will be 20/1.3 = 15.384615
and 15.384
times multiplied by 1.3
is 15.384615385 * 1.3 = 20
therefore this formula is not true, and shows the inability of expressing how modulus operates with float numbers, but by adding up 1.3
and then not passing 20
, it will give 1.3
added 15
times = 19.5
. 6%2 = 0
和7%2 = 1
因为6/2 = 3
次和3*2 = 6
,这就是为什么答案是 0 和 1,但是如果我们使用20 % 1.3
这将是20/1.3 = 15.384615
和15.384
乘以1.3
是15.384615385 * 1.3 = 20
因此这个公式是不正确的,并且表明无法表达模数如何用浮点数运算,但是通过将1.3
加起来然后不传递20
,它将得到1.3
添加15
次 = 19.5
. 20 - 19.5 = 0.5
therefore we have an exact remainder. 20 - 19.5 = 0.5
因此我们有一个精确的余数。
I wanted to know if this approach is correct, and how does Python interprets modulus?我想知道这种方法是否正确,Python 如何解释模数?
20 % 1.3 this will be 20/1.3 = 15,384615 and 15,384 times multiplied by 1,3 is 15,384615385 * 1,3 = 20 therefore this formula is not true…
20 % 1.3 这将是 20/1.3 = 15,384615 和 15,384 乘以 1,3 是 15,384615385 * 1,3 = 20 因此这个公式是不正确的......
I wanted to know if this approach is correct
我想知道这种方法是否正确
Your computation is incomplete;您的计算不完整; therefore the conclusion is wrong.
因此结论是错误的。
You have to take the integer part, ie 15, multiply by 1.3, which gives 19.5, and subtract that from 20. This yields 0.5 as expected.您必须取 integer 部分,即 15,乘以 1.3,得到 19.5,然后从 20 中减去它。这会产生预期的 0.5。
For Python's implementation see float_rem()
.对于 Python 的实现,请参阅
float_rem()
。 It uses fmod()
to compute.它使用
fmod()
来计算。 The output representation is generated by float_repr()
, which calls PyOS_double_to_string()
. output 表示由
float_repr()
生成,它调用PyOS_double_to_string()
。
We get the same output with the C expression printf("%.17g\n", fmod(20, 1.3))
.我们得到相同的 output 和 C 表达式
printf("%.17g\n", fmod(20, 1.3))
。
It shouldn't be a surprise that floating point computation results are sometimes inexact.浮点计算结果有时不准确并不奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.