1

Edit: The floating-point issue has been discussed previously (not only on this site, please see the links below). Therefore this question is essentially a duplicate, however it may be useful to link the well-known floating-point issue to floor division in R.

In this version of R

R version 3.6.3 (2020-02-29) -- "Holding the Windsock"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

I have observed an inconsistency:

> 65 %/% 5
[1] 13
> 6.5 %/% .5
[1] 13
> .65 %/% .05
[1] 12
> .065 %/% .005
[1] 13

It may be a known issue probably related to floating-point arithmetic.

How to deal with this issue in everyday calculations in order to avoid wrong numbers?

Will
  • 247
  • 1
  • 13
  • 1
    Yes, it's a limit of floating point numbers. How to cope with this is really depends on your exact use case. What are you trying to accomplish? It may be best to multiple by a large factor of 10 so you are just working with integers. – MrFlick Nov 02 '20 at 00:01
  • 1
    how about using nomal `/` and then use `round`? PS: I've tried with `trunc` and `as.interger` but you still get that issue. – Edo Nov 02 '20 at 00:06
  • 1
    I'm with @Edo ... `round(c(65,6.5,.65,.065) / c(5,.5,.05,.005), 0)` appears to be reliable/consistent here. It should be noted that despite the expectation of the complementary `%%` operator, `(.65 %% .05)` is ever-so-slightly below `0.05` instead of `0`; so at least the inconsistent behavior here is ... consistent between the `%/%`/`%%` operators. – r2evans Nov 02 '20 at 04:24
  • I learn that since the issue depends on an intrinsic limitation of floating-point numbers, a solution is to avoid them at the offset, that is, to work with integers. Also, I agree that since `/` appears to be more reliable than `%/%` one could avoid to use the latter—however at the cost of renouncing to use this operator. Thanks for the advice, I wonder if there is some kind of 'best way' rooted in computer science or preferred by computer scientists. As a user I would tend to avoid functions that come with strings attached.. – Will Nov 02 '20 at 07:00

1 Answers1

0

As assumed, my question is not new and is intrinsic to floating-point numbers.

As far as I can tell the best way to cope with this issue is to understand it and accept its existence.

More information can be found here, here and here. Then we have the R-FAQ and the R Inferno; I found this links in the mentioned pages.

Will
  • 247
  • 1
  • 13