0

Can anyone explain the strange decimal behavior reproduced below? And how to avoid it? Use rounding I suppose, but I don't see what I should need to.

x <- 200.10 
y <- 200.96
paste("Difference", x - y, sep = ":")
# [1] "Difference:-0.860000000000014"
# But not here!
200.10-200.96
# -0.86
slamballais
  • 3,161
  • 3
  • 18
  • 29
jtdoud
  • 126
  • 7

2 Answers2

1

There is nothing strange going on. The precision in both case are the same just printed differently.

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

The precision in both case is determined by the type (which is double in this case). see https://stat.ethz.ch/R-manual/R-devel/library/base/html/double.html and https://stat.ethz.ch/R-manual/R-devel/library/base/html/zMachine.html

fishtank
  • 3,718
  • 1
  • 14
  • 16
0

This happens when dealing with floating point values because of the number of digits used for precision. You can avoid the problem by ensuring your values have a specific number of decimal places or you may use integers.

LuvnJesus
  • 631
  • 4
  • 9
  • See this post for more info ... http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – LuvnJesus Feb 02 '16 at 23:43
  • there's an important distinction between accuracy and print representation. They're not quite the same. – Ben Bolker Feb 03 '16 at 00:41