Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Floating point numbers cant be compared? [duplicate]

Possible Duplicate:
strange output in comparision of float with float literal

#include<stdio.h>
int main()
{
float me = 1.7;
if(me==1.7)
   printf("C");
else
   printf("C++");
}

Output: C++

Now the reason for this behaviour is said that many floating point numbers cant be represented with absolute precision in binary.

My question is that - If computer thinks and manipulates in binary. Any uncertanity in representation of me would be same for 1.7 when compared. So both should be equal.

ALso how typecasting solves this problem? (float)1.7

like image 823
Shubham Avatar asked Dec 01 '22 10:12

Shubham


2 Answers

You are comparing a float to a double. the literal 1.7 is a double.

You've stored that in a float, which might have less precision than a double, thus the me == 1.7 is comparing 1.7 as a float(promoted to a double) to 1.7 as a double.

In this case, me == 1.7f should make them compare as equal, or changing me to a double double me = 1.7;

In the general case though, you'd want equality to be compared using an epsilon as @duffymo shows.

Also, Obligatory read.

like image 71
nos Avatar answered Dec 14 '22 22:12

nos


Here is some reading material What Every Computer Scientist Should Know About Floating-Point Arithmetic

like image 33
RvdK Avatar answered Dec 14 '22 22:12

RvdK