Python 中 float('inf') 的意义是什么? [英] What is the point of float('inf') in Python?

查看:104
本文介绍了Python 中 float('inf') 的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

例如在选项列表中查找最便宜"的路径:

<预><代码>>>>minimum_path_cost = float('inf')>>># 假设这些是使用一些有价值的算法计算的>>>path_costs = [1, 100, 2000000000000, 50]>>>对于 path_costs 中的路径:...如果路径<最低路径成本:... minimum_path_cost = 路径...>>>最低路径成本1

如果您没有可用的 float('Inf'),您会为 初始最低路径成本 使用什么值?9999999 就足够了 -- float('Inf') 消除了这种猜测.

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?

解决方案

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.

这篇关于Python 中 float('inf') 的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆