浮点数学是否被破坏? [英] Is floating point math broken?

查看:185
本文介绍了浮点数学是否被破坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

0.1 + 0.2 == 0.3
- > false



0.1 + 0.2
- > 0.30000000000000004

为什么会发生这种情况?

解决方案

二进制浮点数就像这样。在大多数编程语言中,它都基于 IEEE 754标准。 JavaScript使用64位浮点表示法,它与Java的 double 相同。问题的症结在于数字以这种格式表示为一个整数乘以二的幂数;分母不是2的幂的有理数(例如 0.1 ,也就是 1/10 )不能准确

在标准 binary64 格式中 0.1 ,可以用十进制表示,也可以写成十进制的



相比之下,有理数 0.1 ,也就是 1/10 ,可以写成

    $
  • 0.1 十进制或
  • 0x1.99999999999999 ... p-4 在一个C99 hexfloat表示法的模拟中,其中 ... 表示一个无止境的9的序列



    • 常量 0.2 0.3 在你的程序中也将近似于他们的真实值。碰巧最接近的 double 到 0.2 大于有理数 0.2 ,但最接近的 double 0.3 小于有理数 0.3 0.1 0.2 的总和大于有理数 0.3 ,因此不同意代码中的常量。

      浮点运算问题的一个相当全面的处理是 每个计算机科学家应该知道什么是浮点运算 。有关更易于理解的解释,请参阅 floating-point-gui.de


      0.1 + 0.2 == 0.3
      -> false
      

      0.1 + 0.2
      -> 0.30000000000000004
      

      Why does this happen?

      解决方案

      Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.

      For 0.1 in the standard binary64 format, the representation can be written exactly as

      • 0.1000000000000000055511151231257827021181583404541015625 in decimal, or
      • 0x1.999999999999ap-4 in C99 hexfloat notation.

      In contrast, the rational number 0.1, which is 1/10, can be written exactly as

      • 0.1 in decimal, or
      • 0x1.99999999999999...p-4 in an analogue of C99 hexfloat notation, where the ... represents an unending sequence of 9's.

      The constants 0.2 and 0.3 in your program will also be approximations to their true values. It happens that the closest double to 0.2 is larger than the rational number 0.2 but that the closest double to 0.3 is smaller than the rational number 0.3. The sum of 0.1 and 0.2 winds up being larger than the rational number 0.3 and hence disagreeing with the constant in your code.

      A fairly comprehensive treatment of floating-point arithmetic issues is What Every Computer Scientist Should Know About Floating-Point Arithmetic. For an easier-to-digest explanation, see floating-point-gui.de.

      这篇关于浮点数学是否被破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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