1

I understand that I could use type() and isinstance() to check if a variable is of a certain type or belongs to certain class. I was wondering if there is a quick way to check if a variable is of a 'numeric' type, similar to isnumeric in MATLAB. It should return True if the variable is int, long, float, double, arrays of ints or floats etc. Any suggestions are greatly appreciated.

Thank you.

Srikanth
  • 769
  • 1
  • 8
  • 14
  • 1
    Array of int/float is not a number. – Hai Vu Aug 04 '14 at 21:34
  • By "array" you mean `numpy` arrays? Or just regular Python lists/tuples/other containers? – kindall Aug 04 '14 at 21:35
  • This might be a duplicate of this: http://stackoverflow.com/questions/3441358/python-most-pythonic-way-to-check-if-an-object-is-a-number – Devarsh Desai Aug 04 '14 at 21:35
  • Check http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable?rq=1 and http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python for isinstance vs type. Also, check http://stackoverflow.com/questions/12466061/how-can-i-check-if-a-string-has-a-numeric-value-in-it-in-python to check for numeric value – fredtantini Aug 04 '14 at 21:35
  • Arrays are not going to be testable this way - what if the fisrt vlue is numeric and the second is a string? If you want to check them all, iterate (or use one of the many helper methods that do the same) – Basic Aug 04 '14 at 21:36
  • Thank you all for your comments! I will use the numbers module. I do mean numpy arrays when I say "array". Guess iterating is the best way forward. Thanks again. – Srikanth Aug 04 '14 at 21:44

2 Answers2

5

The easiest way to check if an object is a number is to do arithmethic operations (such as add 0) and see if we can get away with it:

def isnumeric(obj):
    try:
        obj + 0
        return True
    except TypeError:
        return False

print isnumeric([1,2,3]) # False
print isnumeric(2.5)     # True
print isnumeric('25')    # False
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • @Srikanth, sorry, I've just deleted my comment suggesting this would be a false positive for numpy arrays. Indeed, I hadn't realised you were including numpy arrays as "numbers". – Bruno Aug 04 '14 at 21:51
  • 1
    It still bugs me that I have the right result for the wrong reason :-( – Hai Vu Aug 04 '14 at 21:51
  • @HaiVu especially since this seems to contradict your own comment on the question itself :-) – Bruno Aug 04 '14 at 21:52
  • I stand by my comment: I don't consider an array a number. My solution therefore is not correct. It just happens to produce the right answer for the wrong reason. – Hai Vu Aug 04 '14 at 21:53
  • I agree, but your answer actually answers the question once we read into the details of the question, so that makes is a good answer. – Bruno Aug 04 '14 at 21:57
0

Check to see if each item can be converted to a float:

def mat_isnumeric(input):
    if type(input) is list:
        for item in input:
            if not is_a_number(item):
                return False
        return True
    else:
        return is_a_number(input)

def is_a_number(input):
    try:
        float(input)
        return True
    except ValueError:
        return False

Running the following script:

if __name__ == "__main__":
    print(mat_isnumeric(321354651))
    print(mat_isnumeric(3213543.35135))
    print(mat_isnumeric(['324234324', '2342342', '2343242', '23432.324234']))
    print(mat_isnumeric('asdfasdfsadf'))
    print(mat_isnumeric(['234234', '32432.324324', 'asdfsadfad']))

Produces this result:

True
True
True
False
False
Community
  • 1
  • 1
James Mertz
  • 8,459
  • 11
  • 60
  • 87
  • This will fail for `10**500`. (Setting aside the fact `list` is the only sequence it will work for.) – DSM Aug 04 '14 at 22:00