Is double Multiplication Broken in .NET?

This question already has an answer here:

  • Is floating point math broken? 23 answers

  • Because you've misunderstood floating point arithmetic and how data is stored.

    In fact, your code isn't actually performing any arithmetic at execution time in this particular case - the compiler will have done it, then saved a constant in the generated executable. However, it can't store an exact value of 6.9, because that value cannot be precisely represented in floating point point format, just like 1/3 can't be precisely stored in a finite decimal representation.

    See if this article helps you.


    why doesn't the framework work around this and hide this problem from me and give me the right answer,0.69!!!

    Stop behaving like a dilbert manager, and accept that computers, though cool and awesome, have limits. In your specific case, it doesn't just "hide" the problem, because you have specifically told it not to. The language (the computer) provides alternatives to the format, that you didn't choose. You chose double, which has certain advantages over decimal, and certain downsides. Now, knowing the answer, you're upset that the downsides don't magically disappear.

    As a programmer, you are responsible for hiding this downside from managers, and there are many ways to do that. However, the makers of C# have a responsibility to make floating point work correctly, and correct floating point will occasionally result in incorrect math.

    So will every other number storage method, as we do not have infinite bits. Our job as programmers is to work with limited resources to make cool things happen. They got you 90% of the way there, just get the torch home.


    And 0.69 can easily be represented in binary, one binary number for 69 and another to denote the position of the decimal place.

    I think this is a common mistake - you're thinking of floating point numbers as if they are base-10 (ie decimal - hence my emphasis).

    So - you're thinking that there are two whole-number parts to this double: 69 and divide by 100 to get the decimal place to move - which could also be expressed as:
    69 x 10 to the power of -2 .

    However floats store the 'position of the point' as base-2.

    Your float actually gets stored as:
    68999999999999995 x 2 to the power of some big negative number

    This isn't as much of a problem once you're used to it - most people know and expect that 1/3 can't be expressed accurately as a decimal or percentage. It's just that the fractions that can't be expressed in base-2 are different.

    链接地址: http://www.djcxy.com/p/27438.html

    上一篇: 浮点数精度

    下一篇: .NET中的double multiplication损坏了吗?