将十进制浮点数转换为二进制并返回 [英] Conversion of decimal floating point numbers to binary and back

查看:246
本文介绍了将十进制浮点数转换为二进制并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我的问题是,为什么浮点数中的舍入误差仅在计算后出现而不显示字面量?

My question, in short is, why does rounding error in floats only show up after calculations and not for storage of literals?

我的意思是- 我知道由于从十进制转换为二进制然后返回的浮点数舍入错误而引起的问题.

What I mean is this - I know about the issues that arise due to rounding error in floats when converting from decimal to binary and back.

例如,在Java中:

double a = 10.567;
double b = 2.16;
double c = a * b;

c然后存储值22.824720000000003,而不是22.82472.

c then stores the value 22.824720000000003, instead of 22.82472.

这是因为无法将结果22.82472准确地存储在double类型的有限二进制数字中. 但是,10.567和2.16(即a和b)都不能.

This is because the result 22.82472 cannot be stored accurately in the finite binary digits of the double type. However, neither can 10.567 and 2.16 (i.e. a and b).

但是,如果我打印a和b的值,它们将被精确地打印出来,而没有任何舍入错误.为什么四舍五入错误没有显示在这里?

But if I print the values of a and b, they are printed out exactly, without any rounding error. Why does rounding error not show up here?

这是否意味着float文字的表示形式与float计算结果的表示形式有所不同?

Does this mean that the representation of float literals is somehow different from the representation of float calculation results?

推荐答案

文字转换中存在舍入错误,只是碰巧对您隐藏了. 10.567不能用二进制表示,因此它会四舍五入到最接近的可表示double值,即

There is rounding error in the conversion of literals, it just happens to be hidden from you. 10.567 can't be represented in binary, so instead it rounds to the nearest representable double value which is

10.56700000000000017053025658242404460906982421875

10.56700000000000017053025658242404460906982421875

但是,该算法将打印出尽可能少的数字,而不是打印出确切的值(这很烦人),这样,如果将其转换回二进制,它将给出相同的值(在这种情况下为"10.567")

However rather than printing the exact value (which would be rather annoying), the algorithm prints the fewest possible digits such that if it was converted back to binary it would give the same value (which in this case is "10.567").

事实证明,对于double,您可以对最多15位的任何十进制进行此操作,请参见

It turns out that for doubles, you can do this for any decimal with up to 15 digits, see http://www.exploringbinary.com/number-of-digits-required-for-round-trip-conversions/.

这篇关于将十进制浮点数转换为二进制并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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