point behaviour in a Java program

This question already has an answer here:

  • Is floating point math broken? 23 answers

  • The most common storage for floating-point values in programming languages - IEEE singles and doubles - does not have exact representations for most decimal fractions.

    The reason is that they store values in binary floating-point format, rather than decimal floating-point format. The only fractional values which can be represented exactly are those which are sums of negative powers of two. Numbers like:

  • 0.5 (2^-1)
  • 0.125 (2^-3)
  • 0.625 (2^-1 + 2^-3)
  • Etc.

    What you are seeing is the fact that representations of numbers like 0.96 are not exactly representable, because they are not expressible as a sum of negative powers of two. Thus, when printed out with full precision as a decimal fraction, they won't match the original value.


    另请参阅“每位计算机科学家应了解的浮点数”


    Other answers mentioned why, but not how to avoid it.

    There are several solutions:

  • Scaling: if all your numbers are multiples of 0.01 (for instance), multiply everything by 100 and use integer arithmetic (which is exact).
  • Numeric type: if your language has a numeric type (like a numeric type in SQL), you can use it.
  • Arbitrary precision rationals: use a bignum library like GMP, which allows you to represent these numbers as the ratio of two integers.
  • Decimal floating point: if you have a decimal floating point like the one in IEEE-754r, you can use it.
  • 链接地址: http://www.djcxy.com/p/27454.html

    上一篇: 为什么2.9000000000000004而不是2.9?

    下一篇: 在Java程序中的点行为