문제

The question is simple, why this:

>>> (2**32-1)**2 - 4.0**2 - (2**32-1)**2
0.0
>>> (2**32-1)**2 - (2**32-1)**2 - 4.0**2
-16.0

I know it has to be something about float roundoff error but I need a formal explanation and How can we avoid this such of error?

P/s: Im using python 2.7.3, MacOSX, 64bits

도움이 되었습니까?

해결책

Python int types can outrun your platform word size with ease, but floating point values are tied to the hardware. Don't mix long int and floating point values.

In your first sample, the size of the first integer number far outstrips the maxim precision of floating point numbers.

On a 64bit Mac, the maximum number of decimal digits that a float can represent is 15:

>>> import sys
>>> sys.float_info.dig
15

but your integers use 20 digits. To match the exponent the 16.0 float has to be truncated to 15 significant digits and that means it is basically rounded to 0.

If you have to use floating point arithmetic with long integers, use the decimal.Decimal() type, it is not limited by hardware:

>>> import decimal
>>> (2**32-1)**2 - decimal.Decimal('4.0') ** 2 - (2**32-1)**2
Decimal('-16.00')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top