Search code examples
javamathcode-readability

Java best practice - doing large math calculations on a single line?


I'm wondering about whether it is good to declare multiple unneeded variables to make my code more readable. Which of the following snippets is better coding? it calculates the force between two masses.

    // 1
    double dx = xPos - b.xPos;
    double dy = yPos - b.yPos;
    double r = Math.sqrt(dx*dx + dy*dy);
    double F = G * mass * b.mass / (r*r);

    // 2
    double Fx = G * mass * b.mass / Math.pow( Math.sqrt(Math.pow(2,xPos-b.xPos) + Math.pow(2,yPos-b.yPos)), 2);

How do I balance readability and performance? Is doing it all in one line with a comment okay?

(I realize that the Math.pow( Math.sqrt( in the second example could be removed but this is just an example)


Solution

  • How do I balance readability and performance?

    You have provided a good example of why readability is more important than performance.

    Math.pow(2,xPos-b.xPos)
    

    This is

    2^(xPos-b.xPos)
    

    and not

    (xPos-b.xPos)^2
    

    as I imagine you intended.

    Also

    Math.pow(Math.sqrt(x), 2)
    

    is just

    x
    

    Either way your expression is too complex and you should just simplify it.

    double dx = xPos - b.xPos;
    double dy = yPos - b.yPos;
    double F = G * mass * b.mass / (dx*dx + dy*dy);
    

    Note: both Math.pow and Math.sqrt are expensive operations so by making the formula simpler, it will also be much faster.