[Python-ideas] Way to check for floating point "closeness"?
Ron Adam
ron3200 at gmail.com
Thu Jan 15 22:47:43 CET 2015
On 01/15/2015 01:45 PM, Chris Barker wrote:
> On Thu, Jan 15, 2015 at 9:42 AM, Ron Adam
> <ron3200 at gmail.com
> <mailto:ron3200 at gmail.com>> wrote:
>
> The conservative, "safe" way to handle this is to just treat the error
> function as symmetrical
>
> What if we are not concerned with the location two points are relative
> to zero?
>
>
> not sure what location two points are relative to zero means.
A number relative to zero is it's value. A number relative to another
number is it's distance from the other number. If we divide that from one
of the numbers, we are getting the ratio of their distance from each to the
distance they are from zero.
Seven suggest using the closer one as the divisor so you get a bigger
result, but I prefer the larger one so I get a result between 0 and 1.
A strategy for numbers of different signs may be to swap the sign on the
smaller and add the smaller to the larger... err.. that isn't clear at all.
How about this?
def is_close(x, y, delta=.001):
""" Check is x and y are close to each other. """
if x == y:
return True # Can't get smaller than this.
if x == 0 or y == 0:
return False # Nothing is close to zero.
if abs(x) < abs(y): # Make x the larger one.
x, y = y, x
if x * y < 0: # Signs differ.
x = x - 2.0 * y # Move x and y same distance.
y = -y
return (x - y)/float(x) <= delta
Cheers,
Ron
More information about the Python-ideas
mailing list