Python中float('inf')的意义是什么?
只是想知道在这里,让变量在程序中存储无限值有什么意义?是否有实际用途,并且在任何情况下都更可取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')
消除了这个猜测。