[Python-ideas] Way to check for floating point "closeness"?
Chris Barker
chris.barker at noaa.gov
Thu Jan 15 01:43:44 CET 2015
On Wed, Jan 14, 2015 at 4:05 PM, Ron Adam <ron3200 at gmail.com> wrote:
>
> Did you mean to take this off line?
>
no I really hate mailing lists that don't default to reply to the list --
drives me crazy...
Bringing it back on list.
If I'm checking the tolerance of a resistor, I would measure it's
> resistance and calculate that against it's rated value.
>
> abs(rated-resistance - actual_resistance) / rated_resistance < .05
>
> If they are equal, then I get 0.0. If it's 0, I get 1.0, or 100%.
>
well, I suspect that you never need to check a resistor that is rated for
zero ohms. and if you get one that measures out to zero ohms, it probably
is 100% error, or, in any case not "close" enough. so that's a particular
use case, and I think my idea for a zero_tolerance, which is this case
you'd set to zero, would support that.
But the goal here is a method that will work most of the time, without a
priory knowledge of how large the inputs are likely to be. If you know
that, then you can use an absolute tolerance. You might get that by your
computation above, but you could pass that in to a "close" function -- or
not bother to write a close function, 'cause that's easy anyway.
I would never be comparing a resistor to a rating of 0, and expect any
> reasonable answer. Can you think of a real case which this come up? I
> think it's in the realm of just don't do that.
>
Not in that case, of course, no. But in the general case of checking
whether a computation produces about the same answer as expected (or as it
did before you refactored the code), then zero mught cro up.
But you have a point - maybe we could have a is_close function with a nice
warning in the docs "don't expect this to work with zeros", and still have
somethign useful.
Would raising a ValueError on zero input be too pedantic?
> It might be a case where you need more than two values. You just can't
> assume a relative size with only two numbers.
>
the assumption is relative to the size of the input numbers -- which is
mostly fine, but another way to deal with zero is to (optional) pass in a
"relative to this" parameter -- but that essentially reverts to absolute
tolerance anyway.
Hmm -- new thought -- zero_tolerance can be the Minimum value that you use
for the relative tolerance comparison -- that may be easy and at least give
a continuous result...
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150114/88ea2af4/attachment-0001.html>
More information about the Python-ideas
mailing list