Home > Enterprise >  How to compare floating point number with two other floating point numbers in python?
How to compare floating point number with two other floating point numbers in python?

Time:05-24

When I do the following to compare if the decimal value is between the two values, I get inconsistent results.

x = 1.87

if 1.0 >= x < 2.0:
    print("x: ", x, "; cat: high")
    return 'high'
elif 2.0 >= x < 3.0: 
    print("x: ", x, "; cat: medium")
    return 'medium'
elif 3.0 >= x <= 5.0:
    print("x: ", x, "; cat: low")
    return 'low'
else:
    return None

I get the medium returned as a result. I checked with other values, and none of them matched. I found articles on math.isclose(), but it doesn't help me. How do I solve this?

CodePudding user response:

Consider your conditions:

1.0 >= x < 2.0 says "1.0 is greater than or equal to x and x is less than 2.0." That first bit means that x must be less than or equal to 1.0 and less than 2.0.

If x is greater than or equal to 1.0, this must be false.

2.0 >= x < 3.0 basically implements the same requirement but limits to values of x less than or equal to 2.0.

This is the first condition where x being 1.87 evaluates to true.

CodePudding user response:

The problem is the logic.

x=1.87

1.0 is not >= x, therefore not "high". 2.0 is >= x, and x < 3.0, therefore it is "medium". 3.0 is >= x, and x <5.0, but it never gets there because that's an elif and the condition was True in a previous elif.

Also, I don't see how x being between 1.0-2.0 is high while being between 3.0-5.0 is low...

So:

x = 1.87

if 1.0 <= x < 2.0:
    print("x: ", x, "; cat: low")
    return 'low'
elif 2.0 <= x < 3.0: 
    print("x: ", x, "; cat: medium")
    return 'medium'
elif 3.0 <= x <= 5.0:
    print("x: ", x, "; cat: low")
    return 'high'
else:
    return None
  • Related