Ref Math Inf
## Python math.inf Constant
The `math.inf` constant in Python represents a floating-point positive infinity. To represent negative infinity, you can simply use `-math.inf`.
This constant is equivalent to the output of `float('inf')` and is highly useful for comparison operations, initializing minimum/maximum values in algorithms, and handling mathematical limits.
---
### Syntax
To use the `math.inf` constant, you must first import the `math` module:
```python
import math
math.inf
```
### Return Value
Returns a `float` value representing positive infinity (`inf`).
---
### Code Examples
#### 1. Basic Usage
The following example demonstrates how to access and print positive and negative infinity using the `math` module:
```python
# Import the math module
import math
# Print positive infinity
print(math.inf)
# Print negative infinity
print(-math.inf)
```
**Output:**
```text
inf
-inf
```
#### 2. Practical Application: Finding the Minimum Value
In algorithms (such as finding the shortest path or the minimum value in a collection), `math.inf` is commonly used to initialize a placeholder variable that will be compared against other numbers.
```python
import math
# Initialize the minimum value to positive infinity
min_val = math.inf
numbers = [42, 17, 89, 8, 55]
for num in numbers:
if num < min_val:
min_val = num
print("The minimum value is:", min_val)
```
**Output:**
```text
The minimum value is: 8
```
---
### Key Considerations & Comparisons
* **Type:** The data type of `math.inf` is `float`.
```python
print(type(math.inf)) # Output:
```
* **Comparisons:** Any real number is less than `math.inf`, and any real number is greater than `-math.inf`.
```python
print(999999999 < math.inf) # Output: True
print(-999999999 > -math.inf) # Output: True
```
* **Arithmetic Operations:**
* Adding or multiplying any positive number with `math.inf` still results in `math.inf`.
* Subtracting `math.inf` from `math.inf` results in `nan` (Not a Number).
```python
print(math.inf + 100) # Output: inf
print(math.inf - math.inf) # Output: nan
```
YouTip