×

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

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.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes 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.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.