Tuesday, July 14, 2009

Why cant i use tehse in c++ programming?

why cant i use == or != operators for floating point numbers in c++ programmes?

Why cant i use tehse in c++ programming?
Very good question. To understsnd the answer, you need to know how the float numbers are saved inside the computesr. The float numbers are saved as two different numbers, fraction and power. e.g. 0.05 will be first translated as 5 * 10^-2. And now the numbers 5 and -2 will be saved together. Clearly comparing two float numbers takes comparing these the fraction and the power part. Normally its not the problem with the power, but the fraction part. The computaion of this can make it different. So 5.0 and 5.00 could be different. Infact 5.0 and 4.9999 could be same.
Reply:because floating point are approximated upto certain decimal points, so == does not make sense rather use abs(f1-f2) %26lt; a small number


No comments:

Post a Comment