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

后端 未结 5 1810
滥情空心
滥情空心 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:11

    Instead of using 0 and then you need to handle negative numbers if there is any, float("+inf") and float("-inf") help compare positive or negative infinity like:

    Find the largest value in a dictionary:

    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"
    

提交回复
热议问题