Java的双重计算 [英] java double calculation

查看:40
本文介绍了Java的双重计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道计算机不能精确地表示非整数.因此,当我在Java中添加2个双打时:

I understand that computer can not represent non-integral numbers precisely. so when I add 2 doubles in java for example:

724.64d + 1000d

控制台打印出1724.6399999999999

the console print out 1724.6399999999999

但是为什么要使用 724.64d + 100d 724.64d + 10000d

控制台分别打印出824.64和10724.64吗?

the console print out 824.64 and 10724.64 separately?

当我将两个双打相加时,有什么方法可以知道在什么条件下,总和就是确切的数字吗?

is there a way to know at what condition when I add the 2 doubles, the sum is the exact number ?

之所以问,是因为我们的旧程序使用double进行计算.并使用双重比较来验证数字.例如:让我们说总数为 1849.64 ,所有输入的总和必须等于总数为 1849.64

The reason why I ask is because that our old program use double to do calculation. and use double comparison to validate the numbers. for example: let us say the total is 1849.64, all the inputs amounts added up must be equals to total which is 1849.64

input 1: 724.64
input 2: 1125

将不起作用,因为总和为1849.6399999999999

will not work, because the sum will be 1849.6399999999999

但是如果我们在下面这样输入,则总和为1849.64

but if we input like this below will work, and the sum is 1849.64

input 1: 24.64
input 2: 1825

那么如何找到有效的组合呢?注意,我无权访问此特定的非常旧的程序.当验证失败时,我们必须像第二个输入组合一样手动找到一个四处走动.谢谢.

so how to find those combinations that work? Note, I do not have access to this specific very old program. when the validation failed, we have to manually find a walk around like the second inputs combination. Thanks.

推荐答案

BigDecimal bigDecimal = new BigDecimal(724.64);
bigDecimal = bigDecimal.add(new BigDecimal(1000.0));
System.out.println(bigDecimal.floatValue());<--Works fine 
System.out.println(bigDecimal.doubleValue());<--Works as mentioned in Question

输出:

1724.64
1724.6399999999999

在第一种情况下,它起作用是因为发生了缩小原始转换的情况.但是使用浮点数,您将不得不接受并接受它.

In the first case it works because of narrowing primitive conversion happens. But with Floating-Point numbers you will have to accept and live with it.

正如我所说的,它对于基本体有效的原因

As I stated the reason it is valid for primitives

double d = 724.64;
double d1 = 1000.0;
System.out.println(d + d1);
System.out.println((float) (d + d1));

输出:

1724.64
1724.6399999999999

这篇关于Java的双重计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆