Why does for loop using a double fail to terminate

前端 未结 5 1036
走了就别回头了
走了就别回头了 2020-12-07 00:20

I\'m looking through old exam questions (currently first year of uni.) and I\'m wondering if someone could explain a bit more thoroughly why the following for l

5条回答
  •  盖世英雄少女心
    2020-12-07 01:09

    The number 0.1 cannot be exactly represented in binary, much like 1/3 cannot be exactly represented in decimal, as such you cannot guarantee that:

    0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1==1
    

    This is because in binary:

    0.1=(binary)0.00011001100110011001100110011001....... forever
    

    However a double cannot contain an infinite precision and so, just as we approximate 1/3 to 0.3333333 so must the binary representation approximate 0.1.


    Expanded decimal analogy

    In decimal you may find that

    1/3+1/3+1/3
    =0.333+0.333+0.333
    =0.999
    

    This is exactly the same problem. It should not be seen as a weakness of floating point numbers as our own decimal system has the same difficulties (but for different numbers, someone with a base-3 system would find it strange that we struggled to represent 1/3). It is however an issue to be aware of.

    Demo

    A live demo provided by Andrea Ligios shows these errors building up.

提交回复
热议问题