python: composition of `int` and `float`
As part of some other calculations, I noticed that I sometimes apply float()
and then int()
function to an integer input. Is it safe to assume that:
int(float(x)) == x
开发者_如何学Go
if x is integer?
Why? (Or why not?) And is it documented anywhere?
If x
needs more precision than provided by double-precision floating point numbers then the comparison will fail.
>>> int(float(10**23))
99999999999999991611392L
>>> x = 10**300
>>> int(float(x)) == x
False
Why? (Or why not?) And is it documented anywhere?
One of the definitive guides that every programmer should know well:
What Every Programmer Should Know About Floating-Point Arithmetic
All numbers of the form significant_digits * (2 ** exponent)
have an exact representation as a floating point number, as long as you have enough bits to represent significant_digits
and exponent
. Most platforms use IEEE 754 double representation, and Python uses the platform's double. IEEE 754 doubles have 11 bits for exponent
and 52 bits for significant digits
. As long as your numbers fit these bounds they will come out as expected.
See Python's docs on floating point representation and Wikipedia's article on floating points.
精彩评论