What exactly is "exact" (was Clean Singleton Docstrings)

Chris Angelico rosuav at gmail.com
Tue Jul 19 01:27:24 EDT 2016


On Tue, Jul 19, 2016 at 1:42 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> And then you get these sorts of functions:
>>
>> EPSILON = 0.000001 # Adjust to control numeric accuracy
>> def is_equal(f1, f2, epsilon=EPSILON):
>>     if abs(f1) > abs(f2):
>>         f1, f2 = f2, f1
>>     return abs(f2-f1) < f1*epsilon
>>
>> and interminable debates about how to pick an epsilon, whether it
>> should be relative to the smaller value (as here) or the larger (use
>> f2 instead), or maybe should be an absolute value, or maybe it should
>> be relative to the largest/smallest value that was ever involved in
>> the calculation, or........
>
> Your code is buggy. Consider:
>
> py> is_equal(-1.0, -1.0)
> False

Duh, I got the < and <= bug! Shows how easy it is to get this kind of
function wrong. (Even more so, it shows how easy it is to get code
wrong when you type straight into an email and never test it.)

> Earlier you mentioned "interminable debates
> about how to pick an epsilon", but the reason for that is that it is
> really, really hard to pick an epsilon in any systematic, objective way.

Yeah, and that's the problem. If you're working with some concept of
measurement error, what you actually mean is that every number in your
calculation is actually a range centered on that number; which means
that "equality" really means "overlapping ranges". Epsilon-based
equality is just that, only with a global epsilon instead of one that
actually cares about the real error value. How can that NOT be doomed
to failure?

ChrisA



More information about the Python-list mailing list