[英]What is the point of float('inf') in Python?
在這里只是想知道,讓變量在程序中存儲無限值有什么意義? 是否有任何實際用途,是否存在使用foo = float('inf')
更可取的情況,或者只是為了將其放入其中而插入的一小段代碼?
它充當用於比較的無界上限值。 這對於查找某事物的最低值很有用。 例如,計算遍歷樹木時的路徑路線成本。
例如,在選項列表中查找“最便宜”的路徑:
>>> 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')
消除了這種猜測。
從文檔:
添加了許多浮點功能。 float() 函數現在會將字符串 nan 轉換為 IEEE 754 Not A Number 值,並將 +inf 和 -inf 轉換為正無窮大或負無窮大。 這適用於任何具有 IEEE 754 語義的平台。 (由 Christian Heimes 提供;第 1635 期。)
另請參閱: 使用無窮大和 NaN
float('inf')
如上面的回答所述, float('inf')
用於設置具有無限大值的變量。 簡單來說,它將值設置為+ve infinty 。
或者,我們可以使用以下語句,
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 無窮大。
可以在比較中使用float('inf')
,從而使代碼更簡單明了。 例如,在歸並排序中,一個float('inf')
可以作為標記值添加到子數組的末尾。 不要與數學中無窮大的用法混為一談,畢竟編程不僅僅是數學。
在執行數學運算時, ∞是一個非常關鍵的概念。
float("inf")
或float("INF")
或float("Inf")
或float("inF")
或float("infinity")
創建一個保持無窮大的float
object
float("-inf")
或float("-INF")
或float("-Inf")
或float("-infinity")
創建一個保持負無窮大的浮點數 object
float("NAN")
或float("nan")
或float("Nan")
創建不是數字的float
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
設置為QDoubleSpinBox
的最小值,將+infinity
設置為最大值
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())
而不是使用 0 然后你需要處理負數(如果有的話), float("+inf") 和 float("-inf") 幫助比較正無窮大或負無窮大,如:
查找字典中的最大值:
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.