isfinite()
isfinite(number) returns Boolean , True if the input number is finite, returns False otherwise.
isfinite(n)
Example
import math
print(math.isfinite(2)) # True
print(math.isfinite(-2)) # True
print(math.isfinite(0.0)) # True
print(math.isfinite(0/1)) # True
print(math.isfinite(0.0/1)) # True
Note : 0.0 is considered finite.
import math
print(math.isfinite(float('inf'))) # False
print(math.isfinite(float('-inf'))) # False
print(math.isfinite(float('nan'))) # False
Large Number:
Even large numbers are considered finite.
print(math.isfinite(1e308)) # Output: True
Using Lists:
values = [3.5, float('inf'), -10, float('nan')]
finite_vals = [v for v in values if math.isfinite(v)]
print(finite_vals) # Output: [3.5, -10]
These examples show how math.isfinite() distinguishes between finite numbers and special values like NaN or infinity.
isinf() »
Example 1: Handling Division by Zero
import math
try:
result = 1 / 0
except ZeroDivisionError:
result = float('inf')
print(math.isfinite(result)) # Output: False
Output:
False
Example 4: Handling Infinite Loops with math.isfinite()
import math
def process_data(value):
if not math.isfinite(value):
return "Invalid input: infinite"
return value * 2
print(process_data(float('inf'))) # Output: Invalid input: infinite
Output:
Invalid input: infinite
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com