相同值的R中舍入不一致

问题描述

我在R中有一些非常奇怪的行为,我无法终生解决。最小可行示例如下:

if (!args[0]) return message.channel.send('Please provide a number');

if (Number.isNaN(+args[0])) // if args[0] is not a number
   return message.channel.send('That is not a number');

message.channel.send(+args[0] * 1.31);

输出为:

x <- c(1,1,6,1)
y <- c(0,5)
z <- c(4,2,5)

x90 <- quantile(x,0.9)
y90 <- quantile(y,0.9)
z90 <- quantile(z,0.9)

c(x90,y90,z90)
round(c(x90,z90),0)

有人可以告诉我为什么4.5有时四舍五入为4,但是并非总是如此吗?

一些系统信息:

  • R版本:3.6.2(2019-12-12)
  • RStudio版本:1.1.456
  • 平台: i386-w64-mingw32 / i386(32位)

预先感谢

解决方法

默认情况下,R仅显示7位精度; x90y90z90的所有有效数字都等于4.5到7个有效数字,但是打印更高的有效数字表明x90略大于4.5(因为{{ 3}})。

print(c(x90,y90,z90),digits=20)
                  90%                   90%                   90% 
4.5000000000000008882 4.5000000000000000000 4.5000000000000000000 

为了更深入地理解,您将不得不深入研究分位数计算的细节,但是大多数人(包括我在内)通常将其置于“浮点数学不精确,可以接受”。