Why does for loop using a double fail to terminate

前端 未结 5 1023
走了就别回头了
走了就别回头了 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:01

    Computers (at least current ones) works with binary data. Moreover, there is a length limitation for computers to process in their arithmetic logic units (i.e. 32bits, 64bits etc). Representing integers in binary form is simple on the contrary we cant say the same thing for floating points. 64 bits floating point representation

    As shown above there is a special way of representing floating points according to IEEE-754 which is also accepted as defacto by processor producers and software guys that's why it is important for everyone to know about it.

    If we look at the maximum value of a double in java (Double.MAX_VALUE) is 1.7976931348623157E308 (>10^307). only with 64 bits, huge numbers could be represented however problem is the precision.

    As '==' and '!=' operators compare numbers bitwise, in your case 0.1+0.1+0.1 is not equal to 0.3 in terms of bits they are represented.

    As a conclusion, to fit huge floating point numbers in a few bits clever engineers decided to sacrifice precision. If you are working on floating points you shouldn't use '==' or '!=' unless you are sure what you are doing.

提交回复
热议问题