python check if is infinity

Solutions on MaxInterview for python check if is infinity by the best coders in the world

showing results for - "python check if is infinity"
Savannah
15 Feb 2018
1"Remember to import math!"
2"the math.isinf() can detect if it is an infinity ( - and + inf return true)
3import math
4x = math.inf
5y = -math.inf
6z = 222
7print(math.isinf(x))
8#Expected: True
9print(math.isinf(y))
10#Expected: True
11print(math.isinf(z))
12#Expected: False
13"If you want to only allow +  infinity,"
14def checkplusinf(x):
15  if(x > 0 and math.isinf(x) == True):
16    return True
17  else:
18    return False
19"Or, for minus ifninify"
20def checkminusinf(x):
21  if(x < 0 and math.isinf(x) == True):
22    return True
23  else:
24    return False
25"If you want both"
26def checkplusminusinf(x):
27  if(x > 0 and math.isinf(x) == True):
28    return "input is infinity"
29  elif(x < 0 and math.isinf(x) == True):
30    return "input is -infinity"
31  else:
32    return "input is not infinity."
33print(checkplusminusinf(math.inf))
34#Output: input is infinity
35print(checkplusminusinf(-math.inf))
36#Output: input is -infinity
37print(checkplusminusinf(222))
38#Output: input is not infinity
39print(checkminusinf(-math.inf))
40#Output: True
41print(checkminusinf(math.inf))
42#Output: False
43print(checkminusinf(222))
44#Output: False
45print(checkplusinf(math.inf))
46#Output: True
47print(checkplusinf(-math.inf))
48#Output: False
49print(checkplusinf(222))
50#Output: False