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.
From the documentation:
Many floating-point features were added. The float() function will now turn the string nan into an IEEE 754 Not A Number value, and +inf and -inf into positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes; issue 1635.)
Also refer this: Working with Infinity and NaNs
float('inf')
As stated in answer above, float('inf')
is used for setting a variable with an infinitely large value.
In simple words, it sets the value as +ve infinty.
ALTERNATIVELY, we can make use of the following statement,
import sys
least_value = sys.maxsize
The sys.maxsize is more commonly used, for setting large value initially. When our aim is to find the least value from given set of values.
Also, in case if we want to find largest value from given set of values. We can use the following.
import sys
greatest_value = -sys.maxsize - 1
# logic for comparing with rest of values
The -sys.maxsize - 1
is used for setting initial value as -ve infinity.
float('inf')
can be used in the comparison, thus making the code simpler and clear. For instance, in merge sort, a float('inf')
can be added to the end of subarrays as a sentinel value. Don't confuse with the usage of infinity in maths, after all, programming is not all about maths.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With