0

Consider the following code using a modified rounding function:

round2 = function(x, n) {
  posneg = sign(x)
  z = abs(x)*10^n
  z = z + 0.5
  z = trunc(z)
  z = z/10^n
  z*posneg
}

n<-387.9
d<-400
round2(n/d,4)

The function should return 0.9698, but it returns 0.9697. This seems to occur during the trunc function when 9698 gets truncated to 9697. Is there another rounding function I can use (besides the default round function) to make this value correct?

user3381345
  • 43
  • 1
  • 5
  • what's wrong with the default... – MichaelChirico Feb 19 '16 at 21:11
  • 2
    FWIW, this is simply a standard floating point arithmetic issue. `trunc` isn't doing anything "wrong". If you step through the function and set `options(digits = 19)` and look at the numbers as you go, you'll see that it's just numbers that can't be represented exactly in floating point. – joran Feb 19 '16 at 21:15
  • I agree with all that @joran states, but on the other hand this is a recurring issue, and I don't have the impression that R is performing particularly well in terms of floating-point arithmetics. In Linux, I can use `bc -l` without encountering such problems. There might be room for improvement in future releases. – RHertel Feb 19 '16 at 21:22
  • This is related to: http://stackoverflow.com/questions/12688717/round-up-from-5-in-r and the `?round` states "Note that for rounding off a 5, the IEC 60559 standard is expected to be used, '_go to the even digit_'. Therefore `round(0.5)` is `0` and `round(-1.5)` is `-2`". – fishtank Feb 19 '16 at 21:27
  • Here's an exercise for you: base your function on what the `base` `round` does: https://github.com/wch/r-source/blob/trunk/src/nmath/fround.c#L71-L102 – MichaelChirico Feb 19 '16 at 21:28

0 Answers0