13

I can't figure out how to test if a number is an integer.

I have found IntegerQ, but this function only checks if the type of the input is an integer, not whether the number it represents actually is one (IntegerQ[3.0] returns False).

Element[3.0, Integers] also does not return True.

I'm probably missing something obvious. There must be an easy way to do this.

corey979
  • 23,947
  • 7
  • 58
  • 101
mistercake
  • 241
  • 2
  • 4

4 Answers4

11

you can try this:

integerQ[x_] := x == Round[x]
partida
  • 6,816
  • 22
  • 48
  • 3
    One has to be aware of the approximations that the Equal function makes, though. 1.000000000000001 == Round[1.000000000000001] is true, but 0.000000000000001 == Round[0.000000000000001] is false. – mistercake Jun 04 '17 at 14:50
  • Round@Root[1 + 3 # + 4 #^2 + 2 #^3 + #^4 &, 1, 0] runs into "Internal precision limit". The use of Round makes near-half-integers an issue, which they need not be as they are clearly non-integers. – H.v.M. Jun 27 '21 at 15:00
  • Although Round@N@Root[1 + 3 # + 4 #^2 + 2 #^3 + #^4 &, 1, 0] does not run into this issue. – H.v.M. Jun 27 '21 at 18:46
6
on suggestion of @george2079
checkInteger[num_] := (# === 0. || # === 0) &@FractionalPart[num]
Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42
  • Can you explain why you didn't just use # == 0 instead of (# === 0. || # === 0)? – mistercake Jun 04 '17 at 12:38
  • 1
    @mistercake for your problem it does not matter. you can choose to use == (Equal) instead of === (SameQ). SameQ is usually used to check if two expressions are identical in form. for example 3.0 == 3 will yield True whereas 3.0===3 will yield False – Ali Hashmi Jun 04 '17 at 12:46
  • 1
    @mistercake also checkInteger[num_] := FractionalPart[num] === 0 will not work properly if you use checkInteger[3.0] because 0. === 0 returns False. You can use checkInteger[num_] := FractionalPart[num] == 0 instead – Ali Hashmi Jun 04 '17 at 12:49
  • Does not always, work, for example N[E^(-I Pi/4) + E^(I Pi/4) + E^(-3 I Pi/4) + E^(3 I Pi/4)] yields 2.22045*10^-16 + 0. I and FractionalPart yields the same, so this will not be found to be identical to zero. – H.v.M. Jun 27 '21 at 18:55
4

Define

intQ = IntegerQ@Rationalize@# &;

Then

intQ@3.0

True

and

intQ@2.2

False

corey979
  • 23,947
  • 7
  • 58
  • 101
0

You can also check if your number mod 1 is zero

Wombles
  • 792
  • 3
  • 8
  • 1
    This method has a significant bias in its false positives though. Using f[x_] := (Mod[x, 1] == 0), f[100000000000.000000001] is True while f[99999999999.999999999]. While this isn't likely to be an actual issue in most applications, it is worth remembering that values only slightly above an integer may be reported as integers using this method, while values that are slightly below will almost certainly not be. Every other answer here reports at least one false positive on those 2 numbers though. – eyorble Jul 10 '19 at 19:37