How to Set variable to Inf in Python

in this post, we are going to learn how to Set variables to Inf in Python with examples. The infinite value is defined as an undefined number that is used to initialize the largest positive or negative values and represent by -inf for negative infinite values and Inf for positive infinite values.

1. Set variable to Inf in Python using float()


The python built-in float() function is used to assign infinite values to a variable that can be positive or negative infinite value. We have to just pass string “inf” for positive infinite value “-inf” for negative infinite values as a parameter to float function.

#python 3 peogram to set variable to inf in Python

negInf = float('-inf')
print('negative infinite Value:',negInf)

negInf = float('inf')
print('Postive  infinite value :',negInf)

Output

negative infinite Value: -inf
Postive  infinite value : inf

2. How to Set variable to Inf in Python using np.inf


The Numpy module can also be used to assign infinite values to variables in Python. To use the Numpy module first we have to install it on our system and after installation, we can import it into our program. We will use the numpy library np. inf attribute to assign a variable to a positive infinite value and -np.inf to assign a negative infinite value

import numpy as np
negInf = -np.inf
print('negative infinite Value:',negInf)

negInf = np.inf
print('Postive  infinite value :',negInf)

Output

negative infinite Value: -inf
Postive  infinite value : inf

3. Set variable to infinite using math.inf


We can use Python Math Module math.inf to assign positive infinite values or -math. inf to assign negative infinite values in python. We will import the math module in our program by using “import math” to use its functionality. Let us understand with the below program.

import math
negInf = -math.inf
print('negative infinite Value:',negInf)

negInf = math.inf
print('Postive  infinite value :',negInf)

Output

negative infinite Value: -inf
Postive  infinite value : inf

4. Set variable to infinite using Decimal


In the below python program we have used the Decimal module to set a variable to positive by using “Decimal(‘-Infinity’)” or negative infinite values by using Decimal(‘Infinity’) and print the corresponding values.

from decimal import Decimal


negInf = Decimal('-Infinity')
print('negative infinite Value:',negInf)

posInf = Decimal('Infinity')
print('Postive  infinite value :',posInf)

Output

negative infinite Value: -Infinity
Postive  infinite value : Infinity

Summary

In this post we have learned How to Set variables to Inf in Python by using the numpy library attribute(np.inf,-np.inf), math module attribute(math.inf), and python built-in, decimal module, function float() with examples.