具有粘贴功能的奇怪数字行为
Strange numeric behaviour with paste function
谁能解释下面再现的奇怪的十进制行为?以及如何避免呢?我想使用四舍五入,但我没有看到我应该需要什么。
x <- 200.10
y <- 200.96
paste("Difference", x - y, sep = ":")
# [1] "Difference:-0.860000000000014"
# But not here!
200.10-200.96
# -0.86
由于用于精度的位数,处理浮点值时会发生这种情况。您可以通过确保您的值具有特定的小数位数或者您可以使用整数来避免此问题。
没有什么奇怪的事情发生。两种情况下的精度相同,只是打印方式不同。
sprintf("Difference: %.2f", x - y)
# prints -0.86 as in your last output
options(digits=15); 200.10-200.96
# prints -0.860000000000014 as in your first output
两种情况下的精度均由类型决定(在本例中为 double
)。见 https://stat.ethz.ch/R-manual/R-devel/library/base/html/double.html
和 https://stat.ethz.ch/R-manual/R-devel/library/base/html/zMachine.html
谁能解释下面再现的奇怪的十进制行为?以及如何避免呢?我想使用四舍五入,但我没有看到我应该需要什么。
x <- 200.10
y <- 200.96
paste("Difference", x - y, sep = ":")
# [1] "Difference:-0.860000000000014"
# But not here!
200.10-200.96
# -0.86
由于用于精度的位数,处理浮点值时会发生这种情况。您可以通过确保您的值具有特定的小数位数或者您可以使用整数来避免此问题。
没有什么奇怪的事情发生。两种情况下的精度相同,只是打印方式不同。
sprintf("Difference: %.2f", x - y)
# prints -0.86 as in your last output
options(digits=15); 200.10-200.96
# prints -0.860000000000014 as in your first output
两种情况下的精度均由类型决定(在本例中为 double
)。见 https://stat.ethz.ch/R-manual/R-devel/library/base/html/double.html
和 https://stat.ethz.ch/R-manual/R-devel/library/base/html/zMachine.html