[Python-ideas] Way to check for floating point "closeness"?

Ron Adam ron3200 at gmail.com
Thu Jan 15 08:24:17 CET 2015



On 01/14/2015 11:19 PM, Chris Barker - NOAA Federal wrote:
>> >What Chris is looking for is a way to get a closeness function that works most of the time.
> Exactly.
>
>> >But I don't see how you can do that without specifying some scaler to give it context, and a tolerance.
> Yes, you need a tolerance, sure. And the context comes from the values
> you are comparing. The only problem is what to do with zero. (And
> maybe really near zero).

This is where a good but realistic example of the issue would help. 
Something you may actually see in a specific use case.


>> >     def is_close(a, b, unit, good):
>> >         return (abs(a - b) / unit) <= good But I also think of these sort of things building as building blocks for those more complex systems.  So it may help to consider how they may use these blocks.

>> >
>> >     is_close(218.345, 220, 1, .05)   # OHMs
>> >
>> >     is_close(a, b, ULP, 2)     # ULPs
>> >
>> >     is_close(a, b, AU, .001)   # astronomical units

> I don't get why it helps to introduce units here. I don't think that's
> point (this would all be equally valid with unit less quantities).

> And if you want a scale for relative tolerance that is independent of
> the values you are checking, that's essentially an absolute tolerance.
> I'm not sure it's worth burying that simple calculation in a function.

I agree.  The returned value I was thinking of should have been

     (abs(a - b) / b) / units <= good

Or something like that..  The units here just scales the result. Without 
that you need to either scale the inputs, or scale the tolerance.

In most cases when you are entering a tolerance, you will also be working 
with some multiple of units. But it seems that can confuse as much as it helps.

In any case, I was just trying to come up with some practical example,  and 
at the same time was thinking about how different units of measure can 
effect it.


>>> By using objects we can do a bit more. I seem to recall coming
>>> across  measurement objects some place. They keep a bit more context with them.

> Sure, there are various unit/physical quantities objects out there, many
> numpy-based. But I think is orthogonal to comparing floating point
> numbers. >
>
> And a sime floating point comparison function_may_  belong the
> standard library, but not a more complex physical quantity system

Yes, for the most part I agree, but think such functions would be useful in 
those more complex systems as well.

Ron




More information about the Python-ideas mailing list