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.
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:
19 and 20, say, with an input of 19.5.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With