Search code examples
javafloating-pointdoubleprecisionfloating-accuracy

Java - Be more precise with double


I am currently writing a project for uni, and I was wondering if there are any good practices to be more precise with double values. Namely, is there any difference in precision if I write just a long expression directly in the return statement, or is it better if I split the expression into final variables (making it also more readable, by the way)? For instance, imagine if I had the following formula: Math.sin(a) / Math.cos(b) + Math.tan(c) / d; is it better to write it like follows?

final double sinA = Math.sin(a);
final double cosB = Math.cos(b);
final double tanC = Math.tan(c);
return sinA / cosB + tanC / d;

Thank you in advance!


Solution

  • There won't be any difference if your JVM / JIT is implementing IEEE754 correctly which it is required to by the Java Language Specification.

    Personally I'd write

    double ret = Math.sin(a) / Math.cos(b) + Math.tan(c) / d;
    return ret;
    

    since that allows me to set a line breakpoint on the return ret; statement which allows me to inspect the return value without fancy debugging tools which might not be available to you on a production server at 3am! I find the way you've written it to be unclear: relying on a variable name is more prone to refactoring damage than a standard function name.

    You can trust that the compiler will optimise out the extra variable ret.