乘法是否可以进行短路评估?

Is short-circuit evaluation possible in multiplication?

假设我在Java中有这个代码:

    public static double function(double x, double y, int k) {
        return Math.pow(x, 2) + Math.pow(y, 2) + y + k*Math.sqrt(Math.pow(y, x));
}

它在某个点(x,y)计算一些函数。 注意平方根乘以整数k。在某些情况下,我会给出 k = 0(因为我不需要求平方根)。它给出了我需要的值 问题是我正在编写时间敏感的程序,即我将调用方法 function 很多很多次。所以,我希望我的程序在 k = 0 时不会计算 Math.sqrt(Math.pow(y, x))。 我在谷歌上搜索了一下,但似乎没有 'short-circuit' 等同于算术运算(好吧,在许多情况下它甚至没有意义,乘法可能是一个排除)运算,因为有逻辑运算.

我怎样才能达到预期的效果?

我认为在末尾添加三元运算符将避免调用 Math.sqrt(Math.pow(y, x)) 计算。如下图

 public static double function(double x, double y, int k) {
        return Math.pow(x, 2) + Math.pow(y, 2) + y 
             + ( k!=0 ?  k*Math.pow(y, x/2) : 0); //ternary operator here
}

你可以通过

实现这个结果
k == 0 ? 0 : k*Math.sqrt(Math.pow(y, x))

这不等同于

k*Math.sqrt(Math.pow(y, x))

尽管较短的版本可以生成 NaN,即使 k == 0

没有短路乘法运算符,因为数学不是那样工作的。你可以做的是

result = Math.pow(x, 2) + Math.pow(y, 2) + y;
if (k != 0)
    result += k*Math.sqrt(Math.pow(y, x));
return result;