在 Python 中,float (‘ inf’)的意义是什么?

我只是想知道,让一个变量在程序中存储一个无限值有什么意义呢?是否有任何实际的用途,是否有任何情况下使用 foo = float('inf')会更好,或者仅仅是他们为了放入而插入的一个小片段?

190574 次浏览

它充当比较的无界上限值。这对于查找某物的最低值很有用。例如,在遍历树时计算路径路由成本。

例如,在选项列表中找到“最便宜”的路径:

>>> 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

如果您没有 float('Inf')可用,那么对于 the initial lowest_path_cost您会使用什么值?9999999是否足够—— float('Inf')消除了这种猜测。

来自 文件:

Many floating-point features were added. The float() function will now 将字符串 nan 转换为 IEEE 754 Not A Number 值,并且 + inf 和 -inf into positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes; issue 1635.)

也请参考这个: 使用 Infinity 和 NaNs

可以在比较中使用 float('inf'),从而使代码更简单明了。例如,在合并排序中,可以将 float('inf')作为前哨值添加到子数组的末尾。不要混淆无穷大在数学中的用法,毕竟,编程不全是关于数学的。

float('inf')

如上所述,float('inf')用于设置具有无限大值的变量。 简单来说,它将值设置为 无穷大

另外,我们可以使用以下语句,

import sys
least_value = sys.maxsize

Sys.maxsize更常用于在初始时设置较大的值。当我们的目标是从给定的价值集中找到最小的价值时。

另外,如果我们想从给定的值集中找到最大值,可以使用以下方法。

import sys
greatest_value = -sys.maxsize - 1


# logic for comparing with rest of values

-sys.maxsize - 1用于将初始值设置为-ve 无穷大。

浮点数(“ + inf”)和浮点数(“-inf”)可以帮助比较正无穷大和负无穷大,而不是使用0,如果有的话,还需要处理负数:

查找字典中最大的值:

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"

执行数学运算 无限是一个非常关键的概念。

float("inf")float("INF")float("Inf")float("inF")float("infinity")创建一个包含 无穷大float对象

float("-inf")float("-INF")float("-Inf")float("-infinity")创建一个持有 负无穷大的浮点对象

float("NAN")float("nan")float("Nan")产生持有 not a numberfloat

使用无穷大:

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)

产出:

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

我们可以将 -infinity设置为 最小值,将 +infinity设置为 最大值,设置为 QDoubleSpinBox

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

来源:

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())

窗口:

Open Bank