1

I am trying to find cube root of a set of numbers using following

x^(1/3) %% 1 ==0

but I am not getting the correct value. When I tried to see what is happening in the console found the following behavior :

> 4 %% 1
[1] 0
> 64^(1/3) %% 1
[1] 1

Why is this giving different results? Am I doing something wrong?

harsh atal
  • 411
  • 6
  • 16
  • 1
    If you look at `(64^(1/3) %% 1) == 1`, you'll see that it is not precisely `1`. This is likely a case of floating-point problems, https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal. – r2evans Oct 02 '20 at 22:08
  • Try `as.integer(64^(1/3) ) %% 1` – akrun Oct 02 '20 at 22:09
  • 2
    Also note that while `4^3 == 64` is true, unfortunately `64^(1/3) == 4` is false. While counter-intuitive, this is consistent with the unreliability of floating-point *equality* in any digital computer system that does not implement "arbitrary precision" (i.e., most computer systems/languages). – r2evans Oct 02 '20 at 22:11
  • 1
    If you need integer calculations and integer equality, then the only way you can guarantee rationale (intuitive) equality is to make things actual `integer`s and ensure that R doesn't coerce back to `numeric` (which it can do, silently). Lacking that, floating-point equality works great until it doesn't, without warning or error. The usual recommendation of "tolerance" (e.g., `abs(x - 1) < 1e-8` to approximate `== 1`) doesn't work well with `%%`, so you're likely stuck with akrun's recommendation to use `as.integer`. – r2evans Oct 02 '20 at 22:14

2 Answers2

3

If we convert to integer, it would work

as.integer(64^(1/3) ) %% 1 
akrun
  • 874,273
  • 37
  • 540
  • 662
1

From a mathematical perspective, a workaround is to factorize x first (pracma::factors is used in the following example), e.g.,

nRoot <- function(x, n = 3) {
  u <- pracma::factors(x)
  prod(unique(u)**(table(u) / n))
}

then you will see

> nRoot(64) %% 1
[1] 0

> nRoot(216) %% 1
[1] 0

while

> 64^(1/3) %% 1
[1] 1

> 216^(1/3) %% 1
[1] 1
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81