Search code examples
pythonmath

Check if float result is close to one of the expected values


I have a function in Python makes a number of calculations and returns a float.

I need to validate the float result is close (i.e. +/- 1) to one of 4 possible integers.

For example the expected integers are 20, 50, 80, 100.

If I have result = 19.808954 if would pass the validation test as it is with +/- 1 of 20 which is one of the expected results.

Is there a concise way to do this test? My python math functions are basic.


Solution

  • any(abs(actual - expected) < 1 for expected in [20, 50, 80, 100])
    #   ^^^^^^^^^^^^^^^^^^^^^^^^^^   
    

    This checks if the underlined boolean expression is true for any of the expected values. any will return as soon as it finds a true value and return True or False accordingly.

    If you want to know which expected value it matches, change it to this:

    [expected for expected in [20, 50, 80, 100] if abs(actual - expected) < 1]
    

    This will build a list of matching values:

    • If the list is empty, there was no match.
    • If the list has one element, that's the match.
    • In the edge case that there are multiple matches, the list will have multiple values. This could happen if the expected list had 19 and 20, say, with an input of 19.5.