0

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!

3
  • 1
    imho, the compiler will optimize it anyway so both ways might result in the same bytecode. If you are looking for arbitrary precision, you might want to use BigDecimal Commented Mar 10, 2020 at 16:40
  • Double is precise enough for almost any possible use case. I would ask myself why I think I need more precision and address that. That said if for some reason you do actually need that kind of precision, BigDecimal is the way to go.
    – SephB
    Commented Mar 10, 2020 at 16:54
  • final will just make sure that the variable cannot be assigned to after it is initialized (i.e. set to a value). For local variables that's mainly just to benefit maintenance / readability; it doesn't do anything other than that. Commented Mar 10, 2020 at 16:59

1 Answer 1

2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.