Short-circuit Logic

Chris Angelico rosuav at gmail.com
Wed May 29 23:45:13 EDT 2013


On Thu, May 30, 2013 at 12:28 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> * de facto exact equality testing, only slower and with the *illusion* of
> avoiding equality, e.g. "abs(x-y) < sys.float_info.epsilon" is just a
> long and slow way of saying "x == y" when both numbers are sufficiently
> large;
>

The problem here, I think, is that "epsilon" has two meanings:

* sys.float_info.epsilon, which is an extremely specific value (the
smallest x such that 1.0+x != x)

* the mathematical concept, which is where the other got its name from.

Let's suppose someone is told to compare floating point numbers by
seeing if the absolute value of the difference is less than some
epsilon. They look up "absolute value" and find abs(); they look up
"epsilon" and think they've found it. Trouble is, they've found the
wrong epsilon... and really, there's an engineering issue here too.
Here's one of my favourite examples of equality comparisons:

http://xkcd.com/1047/

# Let's say we measured this accurately to one part in 40
x = one_light_year_in_meters

y = pow(99,8)
x == y  # False
abs(x-y) < x/40  # True

Measurement accuracy is usually far FAR worse than floating-point
accuracy. It's pretty pointless to compare for some kind of "equality"
that ignores this. Say you measure the diameter and circumference of a
circle, accurate to one meter, and got values of 79 and 248; does this
mean that pi is less than 3.14? No - in fact:

pi = 248/79
# math.pi = 3.141592653589793
abs(pi-math.pi) < pi/79  # True

Worst error is 1 in 79, so all comparisons are done with epsilon
derived from that.

ChrisA



More information about the Python-list mailing list