首页 > Java > java教程 > 正文

如果需要准确答案,请避免浮动和双精度

Barbara Streisand
发布: 2024-10-10 08:08:29
原创
767 人浏览过

Item  Evite o float e o double caso sejam necessárias respostas exatas

float 和 double 问题:

  • 专为科学和数学计算而设计,执行二进制浮点运算。
  • 不适合货币计算或需要精确答案的情况。
  • 它们无法准确表示 10 的负幂,例如 0.1,这会导致错误。

示例1:
减去美元金额时计算错误:

System.out.println(1.03 - 0.42);  // Resultado: 0.6100000000000001

登录后复制

示例2:
以每件 10 美分的价格购买 9 件商品时出错:

System.out.println(1.00 - 9 * 0.10);  // Resultado: 0.09999999999999998

登录后复制

即使四舍五入,错误仍然存​​在。
累进计算存在问题,例如以 0.10 到 1.00 的增量价格购买糖果时。

示例 3:
没钱买糖果时犯的错误:

double funds = 1.00;
for (double price = 0.10; funds >= price; price += 0.10) {
    funds -= price;
}
System.out.println(funds);  // Resultado: 0.3999999999999999

登录后复制

解决方案 1:使用 BigDecimal

  • 非常适合财务计算和需要精确度的情况。
  • 避免使用 BigDecimal 的双构造函数,最好使用 String 构造函数。

BigDecimal 示例:

BigDecimal funds = new BigDecimal("1.00");
BigDecimal price = new BigDecimal("0.10");
int itemsBought = 0;

while (funds.compareTo(price) >= 0) {
    funds = funds.subtract(price);
    price = price.add(new BigDecimal("0.10"));
    itemsBought++;
}
System.out.println(itemsBought + " items bought. Money left: " + funds);  
// Resultado: 4 items bought. Money left: 0.00

登录后复制

计算现在很精确。

BigDecimal 的缺点:

  • 使用起来不如原始类型方便。
  • 速度较慢,特别是对于大量操作。

解决方案 2:使用 int 或 long

  • 为了避免准确性问题,请使用 int 或 long 而不是 double 来以美分为单位进行计算。

int 示例(以分为单位):

int funds = 100;  // 1.00 dólar = 100 centavos
int price = 10;   // 0.10 dólar = 10 centavos
int itemsBought = 0;

while (funds >= price) {
    funds -= price;
    price += 10;
    itemsBought++;
}
System.out.println(itemsBought + " items bought. Money left: " + funds);  
// Resultado: 4 items bought. Money left: 0

登录后复制

计算又快又准。

结论:

  • 不要使用 float 或 double 进行需要精确精度的计算。
  • 使用 BigDecimal 进行货币计算或需要小数精度的情况。
  • 使用 int 或 long 进行不涉及大数的金融计算,以分为单位进行计算。

选择:

  • 对于最多 9 位数字,请使用 int。
  • 对于最多 18 位数字,请使用 long。
  • 对于较大数量,请使用 BigDecimal。
  • 此摘要表明,根据上下文,在 BigDecimal、int 或 long 之间进行选择可以优化精度和性能。

以上是如果需要准确答案,请避免浮动和双精度的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!