What is the point of float('inf') in Python?

后端 未结 5 1801
滥情空心
滥情空心 2020-12-02 16:26

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 prefer

5条回答
  •  时光取名叫无心
    2020-12-02 17:06

    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.

提交回复
热议问题