如果没有 if 语句,你如何检查某物是否下降了 10%?

How do you check if something has declined by 10% without an if statement?

我在 Python 中得到两个数字 xy,我被问及 y 是否代表比 x 减少 10% .

没有 if-statement 的最佳方法是什么?我希望将此操作矢量化,所以最好有一个无分支的形式。

详细检查将是:

def check(x,y):
    if x < 0:
        return y < x*1.1
    else:
        return y < x*0.9

我考虑过

def check(x,y):
    return y < x * (1.1 if x < 0 else 0.9)

但这只是一个内联 if-statement

如果我正确理解问题,我认为这应该有效:

def ten_percent_decrease(x: int, y: int):
    """
    check if y is 10% less than x
    """
    return (x - y) / abs(x) > 0.1

注意:如果您为 x 指定 0,代码将中断。我不确定在这种情况下您希望预期的输出是什么,但您可以相应地进行调整。