Floating point arithmetic is too reliable

前端 未结 9 1313
無奈伤痛
無奈伤痛 2021-01-16 09:45

I understand that floating point arithmetic as performed in modern computer systems is not always consistent with real arithmetic. I am trying to contrive a small C# progra

相关标签:
9条回答
  • 2021-01-16 10:06

    Try performing repeated operations on an irrational number (such as a square root) or very long length repeating fraction. You'll quickly see errors accumulate. For instance, compute 1000000*Sqrt(2) vs. Sqrt(2)+Sqrt(2)+...+Sqrt(2).

    0 讨论(0)
  • 2021-01-16 10:07

    My favourite demonstration boils down to

    double d = 0.1;
    d += 0.2;
    d -= 0.3;
    
    Console.WriteLine(d);
    

    The output is not 0.

    0 讨论(0)
  • 2021-01-16 10:07

    The simplest I can think of right now is this:

    class Test
    {
        private static void Main()
        {
            double x = 0.0;
    
            for (int i = 0; i < 10; ++i)
                x += 0.1;
    
            Console.WriteLine("x = {0}, expected x = {1}, x == 1.0 is {2}", x, 1.0, x == 1.0);
            Console.WriteLine("Allowing for a small error: x == 1.0 is {0}", Math.Abs(x - 1.0) < 0.001);
        }
    }
    
    0 讨论(0)
  • 2021-01-16 10:11
    double x = (0.1 * 3) / 3;
    Console.WriteLine("x: {0}", x); // prints "x: 0.1"
    Console.WriteLine("x == 0.1: {0}", x == 0.1); // prints "x == 0.1: False"
    

    Remark: based on this don't make the assumption that floating point arithmetic is unreliable in .NET.

    0 讨论(0)
  • 2021-01-16 10:11

    Try making it so the decimal is not .5.

    Take a look at this article here

    http://floating-point-gui.de/

    0 讨论(0)
  • 2021-01-16 10:13

    I suggest that, if you're truly interested, you take a look any one of a number of pages that discuss floating point numbers, some in gory detail. You will soon realize that, in a computer, they're a compromise, trading off accuracy for range. If you are going to be writing programs that use them, you do need to understand their limitations and problems that can arise if you don't take care. It will be worth your time.

    0 讨论(0)
提交回复
热议问题