只是在这里想知道,在程序中使用变量存储无限值有什么意义?是否有任何实际用途,是否有任何优先使用的情况foo = float('Inf'),或者它只是为了放入它而卡住的小片段?
小智 61
它作为一个无限的上限值进行比较.这对于找到某些东西的最低值很有用.例如,在遍历树时计算路径路径成本.
例如,在选项列表中查找"最便宜"的路径:
>>> 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
Run Code Online (Sandbox Code Playgroud)
如果您没有float('Inf')可用,您将使用什么价值the initial lowest_path_cost?就9999999足够- float('Inf')消除了这个猜测.
Rah*_*thi 11
从文档:
添加了许多浮点功能.float()函数现在将字符串nan转换为IEEE 754 Not A Number值,+ inf和-inf转换为正或负无穷大.这适用于任何具有IEEE 754语义的平台.(供稿人:Christian Heimes;第1635期.)
另请参阅:使用Infinity和NaNs
float('inf')
Run Code Online (Sandbox Code Playgroud)
如上面的回答所述,float('inf')用于设置具有无限大值的变量。简单来说,它将值设置为+ve infinty。
或者,我们可以使用以下语句,
import sys
least_value = sys.maxsize
Run Code Online (Sandbox Code Playgroud)
该了sys.maxsize是比较常用的,用于初始设置较大的值。当我们的目标是从给定的一组值中找到最小值时。
此外,如果我们想从给定的一组值中找到最大值。我们可以使用以下方法。
import sys
greatest_value = -sys.maxsize - 1
# logic for comparing with rest of values
Run Code Online (Sandbox Code Playgroud)
所述-sys.maxsize - 1用于设置的初始值作为-ve无穷大。
| 归档时间: |
|
| 查看次数: |
46226 次 |
| 最近记录: |