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?

- 117
- 9

- 1,643
- 2
- 19
- 20
6 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.

- 5,787
- 1
- 39
- 40
-
9How about the first value from the `path_costs` array? – Solutus Immensus Jun 26 '18 at 08:22
-
8@SolutusImmensus What if path_costs was an empty list? What if path_costs is a generator? In this contrived example the best solution would be lowest_path_cost = min(path_costs) but there's plenty of times you need more complex logic than this where that wouldn't be an option – TheSaint321 Oct 30 '19 at 21:18
-
I've been using None for uninitialized value. It's ugly but it works. I'll start using `float('Inf')` now. – Spidey Dec 16 '19 at 10:21
-
1Can we initialize a large infinite __integer__ ? `int('Inf')` does not work, but `float('Inf')` works fine. – Travis Mar 15 '20 at 12:31
-
2No, because of the binary representation. Integers are stored as the binary representation of a given integer. Floating point values are stored using the IEEE 754 standard, which has special values reserved for +/-infinity, +/- 0, and "NaN" (not a number) – Daniel B. Jun 08 '20 at 20:15
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

- 26,989
- 16
- 82
- 98

- 168,305
- 31
- 280
- 331
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.
-
1I don't recommend this, as `sys.maxsize` refers to the maximum size for sequence indexing, but other numbers could be larger; on a 64-bit platform both `2.0**100` and `2**100` will exceed this (the latter due to Python supporting arbitrary-precision `int`s by default). – HighDiceRoller Aug 30 '22 at 08:37
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.

- 1,950
- 17
- 14
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"
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:

- 2,415
- 2
- 22
- 32