# Different ways to represent infinity in Python

In this tutorial, we will learn the different ways to represent infinity in Python. Many of the times while solving different kinds of programming problems it is common practice to declare the variables with positive infinity or negative infinity.

Suppose that we need to find the maximum value in the array and it is given that all the elements in the array are finite. In this case, will initialize the variable with negative infinity so that we can capture all finite values in the array for finding the maximum.

Below are the different ways to represent infinity in python

## 1. Using float method

In this method, we will use the float function in python to represent infinity.

# representing positive_infinity and negative_infinity using float method positive_infinity = float('inf') negative_infinity = float('-inf') print("Infinity using float method") print("Positive infinity :" , positive_infinity) print("Negative infinity :" , negative_infinity)

Output:

Infinity using float method Positive infinity : inf Negative infinity : -inf

## 2. Using NumPy module in Python

We can represent positive and negative infinity by importing the NumPy module. Below is the implementation using Numpy.

import numpy as np # Positive infinity positive_infinity = np.inf # Negative infinity negative_infinity = -np.inf print("Infinity using numpy") print("Positive infinity :" , positive_infinity) print("Negative infinity :" , negative_infinity)

Output:

Infinity using numpy Positive infinity : inf Negative infinity : -inf

## 3. Using Math Module

Similarly, we can also represent positive and negative infinity by importing the math module. Let’s see the implementation.

import math # Positive infinity positive_infinity = math.inf # Negative infinity negative_infinity = -math.inf print("Infinity using math module") print("Positive infinity :" , positive_infinity) print("Negative infinity :" , negative_infinity)

Output:

Infinity using math module Positive infinity : inf Negative infinity : inf

## 4. Using decimal module

Now, we will represent positive and negative infinity by importing the decimal module. Let’s see the implementation below.

from decimal import Decimal # Positive infinity positive_infinity = Decimal("inf") # Negative infinity negative_infinity = Decimal("-inf") print("Infinity using decimal module") print("Positive infinity :" , positive_infinity) print("Negative infinity :" , negative_infinity)

Output:

Infinity using decimal module Positive infinity : Infinity Negative infinity : -Infinity

Therefore in this tutorial, we have seen 4 different ways to represent infinity in python. So we can use any of the implementations in our python programs.

## Leave a Reply