For numerical comparisons, +- float("inf") should work.

It doesn't always work (but covers the realistic cases):

print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.

To have objects that compare as higher or lower to any other arbitrary objects (including inf, but excluding other cheaters like below), you can create classes that state their max/min-ness in their special methods for comparisons:

class _max:
    def __lt__(self, other): return False
    def __gt__(self, other): return True

class _min:
    def __lt__(self, other): return True
    def __gt__(self, other): return False

MAX, MIN = _max(), _min()

print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]

Of course, it takes more effort to cover the 'or equal' variants. And it will not solve the general problem of being unable to sort a list containing Nones and ints, but that too should be possible with a little wrapping and/or decorate-sort-undecorate magic (e.g. sorting a list of tuples of (typename, value)).

Answer from TryPyPy on Stack Overflow
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Maximum and Minimum float Values in Python | note.nkmk.me
August 11, 2023 - A normalized number is a value whose exponent part is not 0. sys.float_info.min is as follows in hexadecimal.
Top answer
1 of 3
16

For numerical comparisons, +- float("inf") should work.

It doesn't always work (but covers the realistic cases):

print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.

To have objects that compare as higher or lower to any other arbitrary objects (including inf, but excluding other cheaters like below), you can create classes that state their max/min-ness in their special methods for comparisons:

class _max:
    def __lt__(self, other): return False
    def __gt__(self, other): return True

class _min:
    def __lt__(self, other): return True
    def __gt__(self, other): return False

MAX, MIN = _max(), _min()

print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]

Of course, it takes more effort to cover the 'or equal' variants. And it will not solve the general problem of being unable to sort a list containing Nones and ints, but that too should be possible with a little wrapping and/or decorate-sort-undecorate magic (e.g. sorting a list of tuples of (typename, value)).

2 of 3
11

You have the most obvious choices in your question already: float('-inf') and float('inf').

Also, note that None being less than everything and the empty tuple being higher than everything wasn't ever guaranteed in Py2, and, eg, Jython and PyPy are perfectly entitled to use a different ordering if they feel like it. All that is guaranteed is consistency within one running copy of the interpreter - the actual order is arbitrary.

Discussions

floating point - What is the range of values a float can have in Python? - Stack Overflow
What are its smallest and biggest values in python? ... Save this answer. ... Show activity on this post. Copy>>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Smallest positive number machine can store
If we run the following code s=1 while s>0 : print(s) s=s/10 the last output is 10^-323 If we run the following one s=1 a=1+s while a> 1: print(s) s=s/10 a=1+s the last output is 10^-15 The two results appear to be inconsistent. In the second one if I change 1 to 16 (adding 4 bits)and run it ... More on discuss.python.org
๐ŸŒ discuss.python.org
5
0
June 3, 2021
most efficent way of finding the minimum float in a python list - Stack Overflow
Quick question, which is more efficient for finding the smallest number (float) in a long list (10000+ elements) ... I'm going to take a stab that min would not only be semantically more accurate, but will likely be implemented more efficiently since Python will know what to do, and sort() ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to use min() Function for floats - Stack Overflow
I am trying to find out the minimum value within a user define function.The values that are within the loop are float.But somehow I was unable to use min function for my conditional statement.My co... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
W3Resource
w3resource.com โ€บ python-interview โ€บ what-is-the-maximum-and-minimum-value-for-an-int-float-and-string-data-type-in-python.php
Exploring data type limits in Python
August 12, 2023 - Maximum and minimum values for integer and float data types: Max Int: 9223372036854775807 Min Int: -9223372036854775808 Max Float: 1.7976931348623157e+308 Min Float: 2.2250738585072014e-308 Note: The values provided by sys.maxsize and sys.float_info ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-min-max-value-in-float-string-list
Python | Min/Max value in float string list - GeeksforGeeks
April 8, 2023 - Method 1: Using min()/max() + float() This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-25187.html
Python sys.float_info.min value
There is sys.float_info in Python: >>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-3
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ get-the-machine-limits-information-for-float-types-in-python
Get the Machine limits information for float types in Python
February 24, 2022 - Float64 machine limits: Minimum value: -1.7976931348623157e+308 Maximum value: 1.7976931348623157e+308 Machine epsilon: 2.220446049250313e-16 Precision: 15 Smallest positive number: 2.2250738585072014e-308 ยท Use numpy.finfo() to get machine ...
Find elsewhere
๐ŸŒ
DEV Community
dev.to โ€บ frankkk โ€บ python-tips-floatinf-269h
Python Tips- Maximum Value float('inf') - DEV Community
February 3, 2024 - Here is a question: what is the maximum value in Python? For the float, we can use sys.float_info to check the details. >>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) >>> print(sys.float_info.max) 1.7976931348623157e+308 ยท
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ What-is-the-maximum-value-of-float-in-Python
What is the maximum value of float in Python?
Maximum float value: 1.7976931348623157e+308 Minimum positive normalized float: 2.2250738585072014e-308 Float epsilon: 2.220446049250313e-16
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.finfo.html
numpy.finfo โ€” NumPy v2.5 Manual
The number of bits in the exponent portion of the floating point representation. ... The exponent that yields eps. ... The largest representable number. ... The smallest positive power of the base (2) that causes overflow. Corresponds to the C standard MAX_EXP.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Smallest positive number machine can store - Python Help - Discussions on Python.org
June 3, 2021 - If we run the following code s=1 while s>0 : print(s) s=s/10 the last output is 10^-323 If we run the following one s=1 a=1+s while a> 1: print(s) s=s/10 a=1+s the last output is 10^-15 The two results appear to be inconsistent.
Top answer
1 of 3
14

Frst, if you care about performance in Python (which isn't always a sensible thing to care about, but that's another conversation), you should be using the timeit module. Even in C it's hard to predict how certain functions will behave after compilation, and it's harder in Python. People are often confidently expressing opinions about which functions are faster which are data-dependent. Then -- by using timeit, I mean -- you could've found out yourself.

Second, if you really care about performance on lists of floats, you shouldn't be using lists at all, but numpy arrays. Using IPython here, under Python 2.7.2, which makes timing things easy:

In [41]: import random, numpy
In [42]: a = [0.1*i for i in range(10**5)]
In [43]: timeit min(a)
100 loops, best of 3: 4.55 ms per loop
In [44]: timeit sorted(a)[0]
100 loops, best of 3: 4.57 ms per loop
In [45]: random.shuffle(a)
In [46]: timeit min(a)
100 loops, best of 3: 6.06 ms per loop
In [47]: timeit min(a) # to make sure it wasn't a fluke
100 loops, best of 3: 6.07 ms per loop
In [48]: timeit sorted(a)[0]
10 loops, best of 3: 65.9 ms per loop
In [49]: b = numpy.array(a)
In [50]: timeit b.min()
10000 loops, best of 3: 97.5 us per loop

And we note a few things. (1) Python's sort (timsort) works very well on data which has sorted runs, so sorting an already sorted list has almost no penalty. (2) Sorting a random list, on the other hand, is very much slower, and this will only get worse as the data gets larger. (3) Numpy.min() on a float array works sixty times faster than min on a Python list, because it doesn't have to be as general.

2 of 3
12

If the list is already populated, min() is the most efficient way.

There are some tricks you might use in special scenarios:

  • If you build the list from scratch, simply keep the smallest item yet in an external variable, so that the answer will be given in O(1).
  • If there are only Floats in the list, use an Array which gives better performance.
  • You can keep the list sorted using bisect.
  • Use a Python Heap, which even has an efficient implementation of min(). Make sure you understand the effects, mainly a slower insertion. (credit: interjay)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71439176 โ€บ how-to-use-min-function-for-floats
python - How to use min() Function for floats - Stack Overflow
I am trying to find out the minimum value within a user define function.The values that are within the loop are float.But somehow I was unable to use min function for my conditional statement.My code is given below: Copydef life_age(x): for i in range(1,16): if 0<min(x[f'age_{i}'])<18: return 1 ... @paul You should because the if-statement doesn't have a body. This is not legal Python.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ maximum-and-minimum-values-for-integers-in-python
Maximum and Minimum Values for Integers in Python
September 11, 2023 - You can find the maximum and minimum float values using the sys.float_info object, which is part of Python's sys module.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 1265007 โ€บ how-does-max-and-min-function-workequal-float-numbers-in-python
How does max and min function work(equal float numbers) ...
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ find maximum float value in python
Find Maximum Float Value in Python - Spark By {Examples}
May 31, 2024 - How to find the maximum float value in Python? You can find the maximum value of the float data type using the sys.float_info module or the finfo()
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ min
Python min()
min() returns the smallest element from an iterable. ... If the items in an iterable are strings, the smallest item (ordered alphabetically) is returned. languages = ["Python", "C Programming", "Java", "JavaScript"]
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what does stating a variable as float('inf') do?
r/learnpython on Reddit: What does stating a variable as float('inf') do?
August 2, 2020 -

I was doing the following leetcode problem: 121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

My code was as follows:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profits = []
        min_price = 0
        maxprofit = 0
        for p in prices:
            min_price = min(p, min_price)
            max_price = max(p, min_price)
            profit = max_price - min_price
            profits.append(profit)
            maxprofit = max(profits)
        return maxprofit

However it was spitting out the wrong answer on the leetcode website.

So I was wondering why I was getting it wrong so I did a bit of searching and decided to change min_price = 0 to min_price = float('inf').

After that change, the result was accepted by LeetCode. Can someone please tell me why setting min_price to zero is incorrect and what exactly float('inf') does and means in this context?

Top answer
1 of 2
1
float('inf') is infinity. You need that because the minimum of a positive number and zero is always zero, so you are finding the minimum value, you are always returning zero. Though this code is way more complicated than needed. Do you see how you could do this without a for loop?
2 of 2
1
what exactly float('inf') does Standard floating point implementations have an "infinite" value (and also a negative infinite value), that basically compares larger than any non-infinite floating point number. It's akin to MAXINT for integers that have a fixed number of bits (Python ints have an arbitrary number of bits, and thus no maximum integer value). So, in Python float('inf') returns the floating-point infinite value. But that's irrelevant. If min_price is initialized to zero, and your list of input 'prices' are all greater than zero, then your calculation of the minimum price will always be incorrect. Initializing the value to 'inf' ensures that any other non-infinite value will become the new minimum; it's akin to initializing min_price to None, and then checking everytime through the loop whether it is still None or not, and if it is, setting it to an initial value from the 'prices' list. You minimum value has to be one from the 'prices' list for the algorithm to work, not the initialized value. max_price = max(p, min_price) Using the reasoning I just gave you, think about why this is also wrong. There's more wrong, actually. Why are you storing a list of profits, if you are calculating it on each loop? Generally, if you are making a list, you'd find the maximum profit once, after the loop has completed. BTW, what if the maximum price occurs before the minimum price?