Why uint64_t cannot show pow(2, 64) - 1 properly?

前端 未结 2 1058
眼角桃花
眼角桃花 2021-01-29 06:21

I\'m trying to understand why uint64_t type can not show pow(2,64)-1 properly. The cplusplus standard is 199711L.

I checked the pow()

2条回答
  •  自闭症患者
    2021-01-29 06:55

    Floating point numbers have finite precision.

    On your system (and typically, assuming binary64 IEEE-754 format) 18446744073709551615 is not a number that has a representation in the double format. The closest number that does have a representation happens to be 18446744073709551616.

    Subtracting (and adding) together two floating point numbers of wildly different magnitudes usually produces an error. This error can be significant in relation to the smaller operand. In the case of 18446744073709551616. - 1. -> 18446744073709551616. the error of the subtraction is 1, which is in fact the same value as the smaller operand.

    When a floating point value is converted to an integer type, and the value cannot fit in the integer type, the behaviour of the program is undefined - even when the integer type is unsigned.

提交回复
热议问题