简体   繁体   中英

Is short-circuit evaluation possible in multiplication?

Suppose I have this code in 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));
}

It calculates some function at certain point (x,y) . Notice that square root is multiplied by integer k . There will be instances where I will give k = 0 (because I wouldn't need square root evaluated). It gives the value I need but the problem is that I am writing time sensitive program, ie I will call method function many, many times. So, I want that my program wouldn't evaluate Math.sqrt(Math.pow(y, x)) if k = 0 . I googled a bit, but there doesn't seem to be a 'short-circuit' equivalent for arithmetic (well, in many cases it doesn't even make sense, with multiplication possibly being an exclusion) operations as there is for logic operations.

How could I achieve the desired result?

I think adding ternary operator at the end will avoid calling of Math.sqrt(Math.pow(y, x)) computation. As shown below

 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
}

You can achieve this result by doing

k == 0 ? 0 : k*Math.sqrt(Math.pow(y, x))

This is not equivalent to

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

though as the shorter version can produce NaN even when k == 0 .

There isn't a short-circuiting multiplication operator because math just doesn't work that way. What you could do is something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM