×

Python Infinity

Introduction

We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be positive or negative. Any arithmetic operation done on an infinite value, including addition, subtraction, multiplication, and division, will always result in an infinite number.

Python Infinity

Because it has no beginning and hence cannot be represented by an integer, infinity. We are aware that every operation in mathematics that is done on an infinite value will result in an infinite value. The value is displayed as a float. Let's learn about all the ways to represent infinite values, both positive and negative.

The way that numbers are written in Python plays a role in why the infinity data type is a float rather than an int. A binary representation of an integer number is used to represent it; for instance, the value 7 is written as 0111.

However, the float numbers are represented by three components:

The sign:

It's as straightforward as the name. The representation for a positive number is 0, while the symbol for a negative number is 1.

The mantissa:

The set of significant digits in a floating-point integer or a scientific notation is known as the mantissa. Here, the only numbers present are O and 1. A mantissa that has just one 1 to the left of the decimal is said to be normalized.

The exponent:

The exponent field must contain both +ve (positive) and -ve (negative) exponent representations. The real exponent is combined with a bias to get the stored exponent.

This complies with the IEEE 754 specification for a means of storing floating-point numbers. Some values are set aside in the standard to represent special numbers. Infinity is one of these unique numbers.

This standard states that a floating-point integer represents infinity when all of the bits in the exponent and mantissa parts are 1, respectively. Additionally, a sign bit of 1 indicates a negative infinity, while a sign bit of 0 indicates positive infinity.

Since infinity is a unique value, it cannot be represented in a straightforward binary manner. In Python, it has the float datatype instead.

1. Using float(‘inf’) and float(‘-inf’):

Infinity can be expressed as a float('inf') or float('-inf') depending on whether it is positive or negative. The implementationof the previously discussed content is shown in the code below:

Code:

# Defining an infinite +ve number
positive__infinity = float('inf')
print ('Positive Infinity: ', positive__infinity)


# Defining an infinite -ve number
negative__infinity = float('-inf')
print ('Negative Infinity: ', negative__infinity)

Output:

Positive Infinity:  inf
Negative Infinity:  -inf

2. Using Python’s math module:

Python's math library can also be used to represent infinite integers. The code below demonstrates how to do it:

Code:

import math


# Defining an infinite positive number
positive__infinity = math.inf
print ('Positive Infinity: ', positive__infinity)


# Defining an infinite negative number
negative__infinity = -math.inf
print ('Negative Infinity: ', negative__infinity)

Output:

Positive Infinity:  inf
Negative Infinity:  -inf

3. Using Python's decimal module:

The Python decimal module can also be used to express infinite float values.Decimal('Infinity') and Decimal('-Infinity') are used to represent positive and negative infinite values, respectively.

Its implementation is shown in the code below:

Code:

from decimal import Decimal


# Defining an infinite positive number
positive__infinity = Decimal('Infinity')
print ('Positive Infinity: ', positive__infinity)


# Defining an infinite negative number
negative__infinity = Decimal('-Infinity')
print ('Negative Infinity: ', negative__infinity)

Output:

Positive Infinity:  Infinity
Negative Infinity:  -Infinity

4. Utilizing the Numpy library for Python

Infinite values can also be represented using the Numpy module in Python. For positive and negative infinite values, it is used as np.inf and -np.inf, respectively. The code below demonstrates how to express an infinite value using the Numpy library:

Code:

import numpy as np


# Defining an infinite positive number
positive__infinity = np.inf
print ('Positive Infinity: ', positive__infinity)


# Defining an infinite negative number
negative__infinity = -np.inf
print ('Negative Infinity: ', negative__infinity)

Output:

Positive Infinity:  inf
Negative Infinity:  -inf

5. Python Code to Determine whether a Number Is Infinite

The math library's isinf() function, which returns a boolean value, can be used to determine whether a given number is infinite or not. The isinf() method is used in the code below:

Code:

import numpy as np
import math


# Defining an infinite positive number
x = np.inf


# Defining an infinite negative number
y = -np.inf


# Define a finite integer
z = 200


# Check if an in infinite
print (math.isinf(x))


# Check if b in infinite
print (math.isinf(y))


# Check if c in infinite
print (math.isinf(z))

Output:

True
True
False

6. Procedures in arithmetic on an infinite number

Since infinity is a float value, it can be subjected to a variety of mathematical operations. The IEEE standard also defines the outcomes of these procedures.

Code:

# Define positive x value for infinity.
x = float('inf')


# Define negative x value for infinity.
y = float('-inf')


# Working with positive infinity values
print ('For Positive Infinity Value:')
print ('Addition value : ', x + 6)
print ('Subtraction value : ', x - 6)
print ('Multiplication value: ', x * 6)
print ('Division value: ', x / 6)
print ("--------------------------------------------")
# Working with negative infinity values
print ('For Negative Infinity Value:')
print ('Addition value: ', y + 12)
print ('Subtraction value: ', y - 12)
print ('Multiplication value: ', y * 12)
print ('Division value: ', y / 12)

Output:

For Positive Infinity Value:
Addition value :  inf
Subtraction value :  inf
Multiplication value:  inf
Division value:  inf
--------------------------------------------
For Negative Infinity Value:
Addition value:  -inf
Subtraction value:  -inf
Multiplication value:  -inf
Division value:  -inf

7. Python comparison of infinite and finite values

It doesn't get any easier than comparing infinite values to finite values. Like how negative infinity is always lower than negative numbers and positive infinity is always greater than any natural integer. Consider the following code for a better understanding:

Code:

import numpy as np


# X is defined as a positive, infinite integer.
x = np.inf


# y is defined as a positive, infinite integer.
y = -np.inf


# Define finite z positive integer 
z = 200


# Define finite z negative integer
p = -200


# Helper method to make comparisons
def compare (x, y):
 if x>y:
  print ("True")
 else:
  print ("False")


compare (x, y)
compare (x, z)
compare (x, p)
compare (y, z)
compare (y, p)

Output:

True
True
True
False
False

Related Topics

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

How to import pandas in python

How to Install Pandas in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.