简体   繁体   English

Java - 使用 double 更精确

[英]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.我目前正在为 uni 编写一个项目,我想知道是否有任何好的做法可以更精确地使用双值。 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)?也就是说,如果我直接在 return 语句中写一个长表达式,精度是否有任何差异,或者如果我将表达式拆分为final变量(顺便说一下,让它也更具可读性)会更好吗? For instance, imagine if I had the following formula: Math.sin(a) / Math.cos(b) + Math.tan(c) / d ;例如,假设我有以下公式: 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!先感谢您!

There won't be any difference if your JVM / JIT is implementing IEEE754 correctly which it is required to by the Java Language Specification.如果您的 JVM/JIT 正确实现了 Java 语言规范所要求的 IEEE754,则不会有任何区别。

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;因为这允许我在return ret;上设置一个行断点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!该语句允许我检查返回值,而无需花哨的调试工具,这些工具可能在凌晨 3 点在生产服务器上不可用! 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 .您可以相信编译器会优化掉额外的变量ret

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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