Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: max/min builtin functions depend on parameter order

max(float('nan'), 1) evaluates to nan

max(1, float('nan')) evaluates to 1

Is it the intended behavior?


Thanks for the answers.

max raises an exception when the iterable is empty. Why wouldn't Python's max raise an exception when nan is present? Or at least do something useful, like return nan or ignore nan. The current behavior is very unsafe and seems completely unreasonable.

I found an even more surprising consequence of this behavior, so I just posted a related question.

like image 783
max Avatar asked Nov 21 '10 12:11

max


People also ask

How do min and max functions work in Python?

The Python max() function is used to find the largest value in a list of values. The Python min() function is used to find the lowest value in a list. The list of values can contain either strings or numbers. You may encounter a situation where you want to find the minimum or maximum value in a list or a string.

What is the time complexity of MIN () and MAX () method in Python?

To find the maximum or minimum of a sequence, you must look at each element once, thus you can't get better than O(n). Of course, Python min and max have O(n) too: docs. You can write your own min/max function with a for loop and it will have the same complexity, but will be slower because it is not optimized in C.

How many arguments does MIN () take?

You give min three individual arguments, the smallest of which being -1 . So, the return value of the call to min is -1 . Like max , min supports the keyword argument named key so that you can pass objects more complex than numbers into it.

How do you find the max and min of a data set in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.


1 Answers

In [19]: 1>float('nan') Out[19]: False  In [20]: float('nan')>1 Out[20]: False 

The float nan is neither bigger nor smaller than the integer 1. max starts by choosing the first element, and only replaces it when it finds an element which is strictly larger.

In [31]: max(1,float('nan')) Out[31]: 1 

Since nan is not larger than 1, 1 is returned.

In [32]: max(float('nan'),1) Out[32]: nan 

Since 1 is not larger than nan, nan is returned.


PS. Note that np.max treats float('nan') differently:

In [36]: import numpy as np In [91]: np.max([1,float('nan')]) Out[91]: nan  In [92]: np.max([float('nan'),1]) Out[92]: nan 

but if you wish to ignore np.nans, you can use np.nanmax:

In [93]: np.nanmax([1,float('nan')]) Out[93]: 1.0  In [94]: np.nanmax([float('nan'),1]) Out[94]: 1.0 
like image 64
unutbu Avatar answered Sep 17 '22 17:09

unutbu