在 R 中,为什么 %% 对小数的表现不同?

in R, why does %% behave differently for decimal numbers?

在 R 中,我想检查一个数字是否是另一个数字的倍数。这适用于整数

> 124%%1
[1] 0
> 124%%2
[1] 0

但由于某些神秘原因不适用于十进制数,知道为什么 1.05%%0.05 而不是 0 吗?

> 0.05%%0.05
[1] 0
> 1.05%%0.05
[1] 0.05

根据?"%%"

%% and x %/% y can be used for non-integer y, e.g. 1 %/% 0.2, but the results are subject to representation error and so may be platform-dependent. Because the IEC 60559 representation of 0.2 is a binary fraction slightly larger than 0.2, the answer to 1 %/% 0.2 should be 4 but most platforms give 5.

如果您期望结果为 0,那么您可能会对将两个参数乘以 100 的结果感到满意(使这些整数或至少接近它们。)

(100*1.05)%%(100*0.05)
[1] 0

查看@akrun 对“为什么”的回答。