2019-08-14
Best way to have a conditional based on percentage error in Python?
stackoverflow
Question

I am trying to have a loop in Python like this, which makes the if statement execute when the value is less than the lower threshold or greater than upper threshold:-

for i in x_range_original:
  for j in range(0,16):
    lower_threshold = min(df_log[:,j])
    upper_threshold = max(df_log[:,j])

    if df_log[i,j] < lower_threshold or df_log[i,j] > upper_threshold:
      print("Error detected")

However, what I would like to do is have conditions like this:-

if df_log[i,j] within 5 % of lower_threshold or df_log[i,j] within 5 % of upper_threshold:
  print("Error detected")

I know that this accomplished using long statements within the conditional and multiple conditions. But, is there a neat way (say a function which can do the part of within 5 %) to accomplish this, or any way we can do this in minimal lines of code?

Answer
1

You can use chained comparisons:

# lt,ut = lower_threshold, upper_threshold
if((0.95*lt < df_log[i,j] < 1.05*lt) or (0.95*ut < df_log[i,j] < 1.05*ut)):
          print("Error detected")

We can even make it more pythonic as @wjandrea suggests below;

if any(0.95*t < df_log[i,j] < 1.05*t for t in [lt, ut]):
          print("Error detected")
Best way to have a conditional based on percentage error in Python?
See more ...