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

Chris Barker - NOAA Federal chris.barker at noaa.gov
Thu Jan 15 17:06:31 CET 2015

> On Jan 14, 2015, at 11:24 PM, Ron Adam <ron3200 at gmail.com> wrote:
>    (abs(a - b) / b) / units <= good

If units and good are positive, and b is negative, this fails - got to
use abs everywhere. But I'm sure both Steven and my code do that.

>  Without that you need to either scale the inputs, or scale the tolerance.

That's why we want a relative tolerance -- that scales the tolerance
for you -- that's the whole point.
> 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.

Again, relative tolerance takes care of that for you- two values will
have the same relative error whether they are stored in angstroms or
meters -- the exponent will be wildly different, but the mantissas
will be the same, so the relative error doesn't change.

If you want to compare values In Meters According to a tolerance in
angstroms, then you a) want absolute tolerance, and b) want a when
units system.

> 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.

Is_close(computed_value, expected_value, tolerance)

Really does what you want, provided that the inputs are in the same
units, and neither is zero. Tolerance is unitless.

I'll take a look at Steven's code it sound like it's very much like
where I was trying to go.


>>>> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

More information about the Python-ideas mailing list