[Python-ideas] Approximately equal operator

Steven D'Aprano steve at pearwood.info
Sat Jun 16 06:51:30 EDT 2018


On Fri, Jun 15, 2018 at 05:31:57PM -0700, Nathaniel Smith wrote:
> On Fri, Jun 15, 2018 at 3:56 PM, Andre Roberge <andre.roberge at gmail.com> wrote:
> > * people doing heavy numerical work and wanting code as readable as possible
> 
> IME serious numerical work doesn't use approximate equality tests at
> all, except in test assertions.

I wouldn't go that far. It is quite common to write

    abs(x - y) < e

or similar, to see whether x and y are within a certain distance of each 
other. APL even made their equals operator an "approximate equality" 
operator. So I don't think it is completely crazy to want an operator 
for this. But I think that falls short of "a good idea for Python".


> > * teaching mostly beginners about finite precision for floating point
> > arithmetics
> 
> Given that approximate equality tests are almost never the right
> solution, I would be worried that emphasizing them to beginners would
> send them down the wrong path. This is already a common source of
> confusion and trap for non-experts.

Certainly it is an area that is rife with superstitition, like the idea 
that you should "never" compare two floats for equality, or folklore 
about what tolerance you should use.

https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/


> > * people wishing to have trigonometric functions with arguments in degrees,
> > as in a current discussion on this forum.
> 
> AFAICT approximate equality checks aren't really useful for that, no.

Indeed. The last thing a maths library should be doing is making 
arbitrary choices that some value is "close enough" and return "the 
value we think you want".

"Hi, the number you gave is pretty close to 60°, so I'm going to round 
the answer off whether you want me to or not."

Its okay for people to make their own determination what "close enough" 
means, and for many purposes 0.99 could be close enough to 1. But the 
library shouldn't.


[...]
> Python is *very* stingy with adding new operators; IIRC only 3 have
> been added over the last ~30 years (**, //, @). I don't think ~= is
> going to make it.

Exponentiation ** goes back to Python 1.5, so I think that's only two 
new operators :-)



-- 
Steve


More information about the Python-ideas mailing list