简体   繁体   English

初学者使用 BigDecimal 而不是 Double?

[英]Using BigDecimal as a beginner instead of Double?

I am currently learning Java and have stumbled upon the usage of "BigDecimal".我目前正在学习 Java 并偶然发现了“BigDecimal”的用法。 From what I have seen, "BigDecimal" is more precise and therefore it is recommended to use it instead of the normal Double.据我所见,“BigDecimal”更精确,因此建议使用它而不是普通的 Double。

My question is: Should I always use "BigDecimal" over Double because it is always better or does it have some disadvantages?我的问题是:我应该总是使用“BigDecimal”而不是 Double,因为它总是更好还是有一些缺点? And is it worth it for a beginner to switch to "BigDecimal" or is it only recommended when have you more experience with Java?初学者是否值得切换到“BigDecimal”,还是仅在您对 Java 有更多经验时才推荐?

double should be used whenever you are working with real numbers where perfect precision is not required.每当您处理不需要完美精度的实数时,都应该使用double Here are some common examples:以下是一些常见的例子:

  • Computer graphics, for several reasons: exact precision is rarely required, as few monitors have more than a low four-digit number of pixels;计算机图形,有几个原因: 很少需要精确的精度,因为很少有显示器的像素数超过四位数; additionally, most trigonometric functions are available only for float and double , and trigonometry is essential to most graphics work此外,大多数三角函数仅适用于floatdouble ,而三角函数对于大多数图形工作都是必不可少的
  • Statistical analysis;统计分析; metrics like mean and standard deviation are typically expected to have at most a little more precision than the individual data points通常预计平均值和标准差等指标最多比单个数据点具有更高的精度
  • Randomness (eg Random.nextDouble() ), where the point isn't a specific number of digits;随机性(例如Random.nextDouble() ),其中点不是特定的位数; the priority is a real number over some specific distribution优先级是某个特定分布的实数
  • Machine learning, where multiplication factors are being learned and specific decimal precision isn't required机器学习,其中正在学习乘法因子并且不需要特定的小数精度

For values like money, using double at any point at all is a recipe for a bad time.对于像金钱这样的价值,在任何时候都使用double是一个糟糕的时刻。 BigDecimal should generally be used for money and anything else where you care about a specific number of decimal digits, but it has inferior performance and offers fewer mathematical operations. BigDecimal通常应该用于金钱和其他任何您关心特定小数位数的事物,但它的性能较差并且提供的数学运算较少。

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

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