[Python-ideas] Consider adding clip or clamp function to math

Steven D'Aprano steve at pearwood.info
Thu Aug 4 21:35:52 EDT 2016


On Thu, Aug 04, 2016 at 09:46:05PM +0200, Victor Stinner wrote:

> A suggest to start to write a short PEP as the math.is_close() PEP since
> there are subtle issues like NaN (float but also Decimal!) and combinations
> of numerical types (int, float, complex, Decimal, Fraction, numpy scalars
> like float16, ...).
> 
> Maybe a PEP is not needed, I didn't read carefully the thread to check if
> there is a consensus or not.

No consensus.

> I dislike the idea of modifying min() and max() to add special cases for
> float NaN and decimal NaN.

min() and max() currently return NANs when given a NAN and number, but I 
don't know if that is deliberate or accidental.

The IEEE-754 standard says that min(x, NAN) and max(x, NAN) should 
return x.

https://en.wikipedia.org/wiki/IEEE_754_revision#min_and_max


> Which type do you expect for fmax(int, int)? Should it be int or float?

int.

> Should fmax(Decimal, float) raise an error, return a float or return a
> Decimal?

Comparisons between float and Decimal no longer raise:

py> Decimal(1) < 1.0
False

so I would expect that fmax would return the larger of the two. If the 
larger is a float, it should return a float. If the larger is a Decimal, 
it should return a Decimal. If the two values are equal, it's okay to 
pick an arbitrary one.



-- 
Steve


More information about the Python-ideas mailing list