1
isinteger(sqrt(3))
0
isinteger(sqrt(4))
0

Both answers give zero. The answers must be:

isinteger(sqrt(3))
0
isinteger(sqrt(4))
1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
challote
  • 35
  • 4
  • 3
    To avoid floating point issues, try `integer y` and `y = int(sqrt(x))`. Then see if `y*y` is equal to `x`. – L. Scott Johnson Jul 18 '22 at 16:10
  • 2
    int( ) is an integration function in MATLAB. You could use round( ) instead. – James Tursa Jul 19 '22 at 00:13
  • Please read the descriptions of both [tag:matlab] and [tag:octave]. They are **not** the same, thus please only use both tags when asking about the similarities/differences between the two. Using both tags could result in answers being incompatible to the other software, unnecessarily forcing answerers to check validity of their code in both programs. – Adriaan Jul 28 '22 at 09:35

3 Answers3

5

isinteger checks for type. integer is a type of variable, not a property of a number. e.g. isinteger(2.0) returns 0.

Try:

mod(sqrt(x),1) == 0

However, you may still have issues with this due to numerical precision.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
3

You may do as well

y = sqrt(4);
y==round(y)

or to take round-off error into account with a (2*eps) relative tolerance

abs(y-round(y)) <= 2*eps*y
S. Gougeon
  • 791
  • 3
  • 16
3

Others have touched on this, but you need to be careful that floating point effects are taken into account for your application. Limited precision issues can give unexpected results. E.g., take this example:

enter image description here

Here you start with a non-integer value that is very close to 4 (x). The square root of this number in double precision is exactly 2 (y), but squaring this number does not equal the original x. So the calculated square root y is exactly an integer, but it really isn't indicative of the situation since the original x isn't an integer. The actual square root of x isn't an integer even though the floating point calculation of sqrt(x) is exactly an integer.

What if we also checked to see if the original x is an integer? Well, take this example:

enter image description here

Here the original x is so large that every floating point number near x is an integer, so the x+eps(x) is an integer. The calculated square root in double precision is also an integer (y). But even though both are integers, y*y does not equal x. Again we have the situation where the actual square root of x isn't an integer, but the floating point calculated value of sqrt(x) is exactly an integer.

So, bottom line is this can be a bit trickier than you might have anticipated. We don't know your application, but you might want to check that both x and y are integers and that y*y == x is true before convincing yourself that the square root of x is an integer. And even then, there might be cases where all these checks pass but still there is a discrepancy that floating point effects simply didn't uncover.

James Tursa
  • 2,242
  • 8
  • 9