当我使用模运算符时,我注意到一些非常奇怪的浮点算术行为.如果我评估58 mod 2,我可以(并且应该)得到0.
> 58 %% 2
[1] 0
Run Code Online (Sandbox Code Playgroud)
这并不奇怪.但是如果"58"是某些浮点算术运算的结果呢?以下产生2的无意义结果.
> (0.58*100) %% 2
[1] 2
Run Code Online (Sandbox Code Playgroud)
我不确定为什么任何mod 2产生2都没关系,但我认为这可能是尝试修改非整数的结果.所以我试着强迫.
> as.integer(0.58*100) %% 2
[1] 1
Run Code Online (Sandbox Code Playgroud)
当我评估as.integer参数的上限时,这似乎是有意义的.
ceiling(as.integer(0.58*100))
[1] 57
Run Code Online (Sandbox Code Playgroud)
这没有任何意义,但更糟糕的是,它甚至不一致.
> ceiling(as.integer(0.58*100))
[1] 57
> ceiling(as.integer(0.57*100))
[1] 56
> ceiling(as.integer(0.56*100))
[1] 56
> ceiling(as.integer(0.55*100))
[1] 55
Run Code Online (Sandbox Code Playgroud)
最后,似乎序列生成的数字根据序列的长度表现不同!
> sapply(seq(from=0.55, to=0.58, by = 0.01), function(x)
ceiling(as.integer(100*x)))
[1] 55 56 57 57
> sapply(seq(from=0.55, to=0.59, by = 0.01), function(x)
ceiling(as.integer(100*x)))
[1] 55 56 57 58 59
Run Code Online (Sandbox Code Playgroud)
有没有办法让我乘以两个数字,并将结果强制转换为一个整数,其上限等于我从as.integer得到的整数值?