What is the point of float('inf') in Python?

Question:

Just wondering over here, what is the point of having a variable store an infinite value in a program? Is there any actual use and is there any case where it would be preferable to use foo = float('inf'), or is it just a little snippet they stuck in for the sake of putting it in?

Asked By: Nirvik Baruah

||

Answers:

It acts as an unbounded upper value for comparison. This is useful for finding lowest values for something. for example, calculating path route costs when traversing trees.

e.g. Finding the “cheapest” path in a list of options:

>>> lowest_path_cost = float('inf')
>>> # pretend that these were calculated using some worthwhile algorithm
>>> path_costs = [1, 100, 2000000000000, 50]
>>> for path in path_costs:
...   if path < lowest_path_cost:
...     lowest_path_cost = path
...
>>> lowest_path_cost
1

if you didn’t have float('Inf') available to you, what value would you use for the initial lowest_path_cost? Would 9999999 be enough — float('Inf') removes this guesswork.

Answered By: user559633

From the documentation:

Many floating-point features were added. The float() function will now
turn the string nan into an IEEE 754 Not A Number value, and +inf and
-inf into positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes; issue
1635.)

Also refer this: Working with Infinity and NaNs

Answered By: Rahul Tripathi

float('inf') can be used in the comparison, thus making the code simpler and clear. For instance, in merge sort, a float('inf') can be added to the end of subarrays as a sentinel value. Don’t confuse with the usage of infinity in maths, after all, programming is not all about maths.

Answered By: Yossarian42
float('inf')

As stated in answer above, float('inf') is used for setting a variable with an infinitely large value.
In simple words, it sets the value as +ve infinty.

ALTERNATIVELY, we can make use of the following statement,

import sys
least_value = sys.maxsize

The sys.maxsize is more commonly used, for setting large value initially. When our aim is to find the least value from given set of values.

Also, in case if we want to find largest value from given set of values. We can use the following.

import sys
greatest_value = -sys.maxsize - 1

# logic for comparing with rest of values

The -sys.maxsize - 1 is used for setting initial value as -ve infinity.

Answered By: Optider

Instead of using 0 and then you need to handle negative numbers if there is any, float(“+inf”) and float(“-inf”) help compare positive or negative infinity like:

Find the largest value in a dictionary:

def max_key(my_dict):
    largest_key = float("-inf")
    largest_value = float("-inf")

    for key, value in my_dict.items():
      if value > largest_value:
          largest_value = value
          largest_key = key
    return largest_key


print(max_key({1:100, 2:1, 3:4, 4:10}))      # should print 1

print(max_key({"a":100, "b":10, "c":1000}))  # should print "c"
Answered By: Kasem777

While performing mathematical operations is a very crucial concept.

float("inf") or float("INF") or float("Inf") or float("inF") or float("infinity") creates a float object holding infinity

float("-inf") or float("-INF") or float("-Inf") or float("-infinity") creates a float object holding negative infinity

float("NAN") or float("nan") or float("Nan") creates float holding not a number

Using infinity:

import math

_pos_infinity = float("INF")#Positive infinity
_neg_infinity = float("-INF")#Negative infinity
_nan = float("NAN")#Not a number

print(_pos_infinity, _neg_infinity, _nan)#inf -inf nan


"""
SincePython 3.5 you can use math.inf
Use math.isinf and math.isnan method to identify number
"""

print(math.isinf(_pos_infinity))#True
print(math.isnan(_pos_infinity))#False
print(math.isnan(_nan))#True

"""
Arithmetic operation
"""

print(_pos_infinity / _pos_infinity)#nan
print(_pos_infinity + 1)#inf
print(_neg_infinity + 1)#-inf
print(_neg_infinity - _neg_infinity)#nan, Since +infinity -infinity is indeterminate and undefined. Don't overthink infinity is a concept.
print(1 / _pos_infinity)#0.0 since 1/∞ is 0
print(1 / _neg_infinity)#-0.0
print(_pos_infinity * _neg_infinity)#-inf , A positive times a negative is a negative.
print(_neg_infinity * _neg_infinity)#inf, A negative times a negative is positive


try:
    val = 1/(1/_pos_infinity) # 1/∞ is 0 & 1/0 will raise ZeroDivisionError
    print("This line is not executed")
except ZeroDivisionError as err:
    print(err)

Output:

$ python3 floating.py 
inf -inf nan
True
False
True
nan
inf
-inf
nan
0.0
-0.0
-inf
inf
float division by zero

We can set -infinity as the minimum value and +infinity as maximum value to a QDoubleSpinBox

box = QDoubleSpinBox()
box.setMinimum(float("-inf"))
box.setMaximum(float("inf"))

Source:

import sys

from PySide6.QtWidgets import QMainWindow, QApplication, QDoubleSpinBox, QWidget, QFormLayout, QLineEdit, QPushButton


def getDoubleSpinBox() -> QDoubleSpinBox:
    box = QDoubleSpinBox()
    box.setMinimum(float("-inf"))
    box.setMaximum(float("inf"))
    box.setSingleStep(0.05)
    box.setValue(100)
    return box


def getLineEdit(placehoder: str, password: bool = False):
    lineEdit = QLineEdit()
    lineEdit.setPlaceholderText(placehoder)
    if password:
        lineEdit.setEchoMode(QLineEdit.Password)
    return lineEdit


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Open Bank")
        self.widget = QWidget()
        self.widgetLayout = QFormLayout()
        self.widgetLayout.addRow("ID", getLineEdit(placehoder="Investor name"))
        self.widgetLayout.addRow("Investment", getDoubleSpinBox())
        self.widgetLayout.addRow("Password", getLineEdit(placehoder="Enter secret password", password=True))
        self.widgetLayout.addRow(QPushButton("Invest"), QPushButton("Cancel"))
        self.widget.setLayout(self.widgetLayout)
        self.setCentralWidget(self.widget)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())

Window:

Open Bank

Answered By: Udesh Ranjan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.