YouTip LogoYouTip

Ref Math Isfinite

## Python math.isfinite() Method The `math.isfinite()` method is a built-in function in Python's standard `math` module. It is used to determine whether a given number is finite. A number is considered **finite** if it is neither infinity (positive or negative) nor a NaN (Not a Number) value. --- ### Introduction In scientific computing, data analysis, and general programming, you often encounter special floating-point values such as positive infinity (`inf`), negative infinity (`-inf`), and Not-a-Number (`NaN`). The `math.isfinite()` method provides a reliable, built-in way to validate your numeric data before performing mathematical operations that might otherwise fail or produce invalid results. * **Python Version Added:** 3.2 --- ### Syntax ```python import math math.isfinite(x) ``` #### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **x** | `float` or `int` | **Required.** The numeric value to check. | > **Note:** If `x` is not a number (e.g., a string, list, or dictionary), the method will raise a `TypeError`. #### Return Value * Returns **`True`** if `x` is a finite number (neither infinity nor NaN). * Returns **`False`** if `x` is positive infinity, negative infinity, or NaN. --- ### Code Examples The following example demonstrates how to use `math.isfinite()` to check various types of numeric values, including standard integers, floats, infinities, and NaN. ```python import math # Check standard finite numbers print(math.isfinite(2000)) # Output: True print(math.isfinite(-45.34)) # Output: True print(math.isfinite(+45.34)) # Output: True print(math.isfinite(0.0)) # Output: True # Check infinity constants from the math module print(math.isfinite(math.inf)) # Output: False print(math.isfinite(-math.inf)) # Output: False # Check parsed string representations of NaN and Infinity print(math.isfinite(float("nan"))) # Output: False print(math.isfinite(float("inf"))) # Output: False print(math.isfinite(float("-inf"))) # Output: False ``` #### Output: ```text True True True True False False False False False ``` --- ### Considerations and Best Practices 1. **Handling Non-Numeric Types:** If you pass a non-numeric type to `math.isfinite()`, Python will raise a `TypeError`. If your input data might contain non-numeric types, wrap the call in a `try-except` block: ```python import math value = "123" # String type try: is_finite = math.isfinite(value) except TypeError: print("The input is not a valid numeric type.") ``` 2. **Difference from `math.isinf()` and `math.isnan()`:** * `math.isfinite(x)` returns `True` only if the number is a normal, valid real number. * `math.isinf(x)` returns `True` *only* if the number is positive or negative infinity. * `math.isnan(x)` returns `True` *only* if the number is NaN. Essentially, `math.isfinite(x)` is equivalent to: ```python not math.isinf(x) and not math.isnan(x) ```
← Ref Math IsnanRef Math Sqrt β†’