0

How can I test if the square root of a number is an integer using R?

The following all evaluate to FALSE.

is.integer( sqrt(25) )
is.integer( sqrt(25L) )
Bastiaan Quast
  • 2,802
  • 1
  • 24
  • 50

1 Answers1

1

Ok, I found a work around, but I'm not sure if it's efficient or even robust to using more exotic numbers.

25 %% sqrt(25) == 0

Evaluates to TRUE.

Perhaps a better way of doing this would be:

sqrt(25) %% 1 == 0

Which also evaluates to TRUE. Adapted from this answer.

Community
  • 1
  • 1
Bastiaan Quast
  • 2,802
  • 1
  • 24
  • 50
  • 2
    You should check `?is.integer`, particularly the function `is.wholenumber` defined in the "Examples" section. –  Jun 10 '15 at 07:57
  • 1
    if your square root is not an integer then you would be doing integer dvision with non integer, which is not a good idea and if it is an integer, the square root definition is that sqrt(k)*sqrt(k)==k so it will always be TRUE. Sorry but I have to downvote this very wrong "answer". @Pascal, why did you delete your answer? – Cath Jun 10 '15 at 08:15
  • thanks @Pascal I've looked at the `is.wholenumber` example but I didn't think that that was very clear or exactly what I was looking for. – Bastiaan Quast Jun 10 '15 at 09:01
  • 1
    @CathG thanks, I don't really agree with you, from the R documentation `%% and x %/% y can be used for non-integer y, e.g. 1 %/% 0.2,`. However, I have updated my answer with an alternative which uses 1. – Bastiaan Quast Jun 10 '15 at 09:03
  • 1
    @CathG I don't understand the statement that "a number will always be 0 modulo to its square root". I can only see that being true when the result is an integer. `3 %% sqrt(3)` is not 0, and if a square root isn't an integer it can't give a modulo 0 for its square since it needs to be multiplied by another non-integer (i.e. will have a remainder). Am I being silly? – ping Jun 10 '15 at 09:44
  • right, good point, I am "stupidely" thinking of integer multiplication with integers, I have a mathematical background and it seems my head doesn't want to imagine we can do "%%" with non integers............ ;-) – Cath Jun 10 '15 at 09:57
  • @bquast, yes they can "but the results are subject to representation error" and it's mathematically wrong... also, try `sqrt(8+1/3+1/3+1/3) %% 1 == 0` or `(8+1/3+1/3+1/3)%%sqrt(8+1/3+1/3+1/3)` – Cath Jun 10 '15 at 09:59