In c++, how to know when a decimal number can be exactly representing using IEEE 754-1985 standard.
for instance 0.2 cannot be representing exactly.
Is there a simple rule ?
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.
A number can be represented exactly as an IEEE755 float if it can be written as B × 2n, where B is an integer (and B and n fall into some valid range). In other words, there must be some integer n such that if you mutliply your number by 2n you get an integer. Clearly for 1/5 there is no such n.
Yet another way of saying it is that your number has to be the sum of finitely many powers of two which are not too far apart (the maximal distance between the powers is the precision of your float).
Yet another way to say it very loosely is that “rational numbers whose denominator is a power of two” are representably (though with the obvious precision constraints).
The precision of the float, which is the width of B, is 24 bits for single, 53 bits for double and 64 bits for extended double precision.