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
if x is integer?
Why? (Or why not?) And is it documented anywhere?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 representsignificant_digitsandexponent. Most platforms use IEEE 754 double representation, and Python uses the platform’s double. IEEE 754 doubles have 11 bits forexponentand 52 bits forsignificant 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.