-1

In Python, How can I compare two float variable values to ensure if they are within a certain tolerance of each other?

For example:

variable = 17.40
array = [14.40, 14.12, 45.50]

I need to compare the variable value with the array elements to see which one are close enough.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Rohit Goel
  • 3,396
  • 8
  • 56
  • 107
  • 3
    Also, could you clarify what it is is you're trying to do? – Matt Feb 21 '13 at 10:43
  • Given this question he also asked: http://stackoverflow.com/questions/15000021/how-to-compare-float-value-in-in-django I'm guessing the problem is that the numbers in the array are floats and float comparison doesn't work too well if you use `==` as rounding errors can mess you up(try doing `17.1+0.3==17.4` and you'll get `False` – entropy Feb 21 '13 at 10:48

1 Answers1

2

From this question that you also asked. Here's a piece of code that will check if your variable is in the array(unless that's not what you meant by compare the variable value with the array elements):

TOLERANCE=10**-6

def are_floats_equal(a,b):
  return abs(a-b) <= TOLERANCE

def float_in_array(number, array):
  return True in [are_floats_equal(number, a) for a in array]

Edit. This might be a bit more efficient to do this way(though less succinct) as we only loop over the array once:

def float_in_array(number, array):
  for a in array:
    if are_floats_equal(number, a):
      return True
  return False
Community
  • 1
  • 1
entropy
  • 3,134
  • 20
  • 20
  • 2
    My guess is that he asked two questions about the same problem he's facing is and he's not very good at fully expressing what the problem is. But I may be wrong and this is just a guess. – entropy Feb 21 '13 at 10:52
  • 1
    This is what `any` is for: `any(are_floats_equal(number, a) for a in array)`. (Although just like you, I'm not sure whether this is what the OP means by 'compare'; for all I know he wants a list of of differences.) – DSM Feb 21 '13 at 12:04
  • Oh, nice, I didn't know about any. Been using Python for ages as my go to language and yet I still learn new things about it :-) – entropy Feb 21 '13 at 18:12