安卓:java的舍入误差。不明白为什么? [英] Android: java rounding error. Can't understand why?

查看:209
本文介绍了安卓:java的舍入误差。不明白为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人能解释为什么地球上的这些同EX pressions返回的值不同?

Can anybody explain why on Earth these "same" expressions returns different values?

(new BigDecimal(String.valueOf(131.7d))).multiply(new BigDecimal(String.valueOf(0.95d))).doubleValue() = 125.115

(new BigDecimal(               131.7d )).multiply(new BigDecimal(               0.95d )).doubleValue() = 125.11499999999998

什么的BigDecimal正在做他们之间有什么不同?

What BigDecimal is doing different between them?

推荐答案

如果你读了API文档,你会发现taht 将String.valueOf(dobule)使用 Double.toString(双)来格式化值。这也许并不明显,但 Double.toString(双)舍入值,格式化为一个字符串之前:

If you read the API documentation, you will find taht String.valueOf(dobule) uses Double.toString(double) to format the value. It's perhaps not obvious, but Double.toString(double) rounds the value, before formatting it as a string:

多少位必须印为M或一个小数部分?
  必须有至少一个数字重新present小数部分,并
  除此之外,尽可能多的,但是只有尽可能多,更多的数字能根据需要
  唯一区分类型的相邻值的参数值
  双。也就是说,假设x是精确的数学值
  再由该方法制备的小数重新presentation psented $ P $
  有限的非零参数d调用。那么d一定是最接近的双重价值
  为x;如果两个double值都同样接近x,那么D必须
  他们中的一个和D必须的有效数字的最低位显著
  为0。

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

这样做的结果是,将String.valueOf(131.7d)将返回字符串131.7,即使参数的精确值131.69999999999998863131622783839702606201171875。这样做的原因是,小数不能总是被重新presented究竟使用二进制小数(与浮子使用并增加一倍)。

The result of this is that String.valueOf(131.7d) will return the string "131.7" even if the exact value of the argument is 131.69999999999998863131622783839702606201171875. The reason for this is that decimal fractions cannot always be represented exactly using binary fractions (as used with floats and doubles).

所以,新的新的BigDecimal(将String.valueOf(131.7))将创建一个BigDecimal与精确值131.7。 新的BigDecimal(131.7)将创建一个BigDecimal与精确值131.69999999999998863131622783839702606201171875。

So, new new BigDecimal(String.valueOf(131.7)) will create a BigDecimal with the exact value 131.7. new BigDecimal(131.7) will create a BigDecimal with the exact value 131.69999999999998863131622783839702606201171875.

这篇关于安卓:java的舍入误差。不明白为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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