Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of float and double variables [duplicate]

Possible Duplicates:
Difference between float and double
strange output in comparision of float with float literal

I am using visual C++ 6.0 and in a program I am comparing float and double variables For example for this program

#include<stdio.h>
int main()  
{    
    float a = 0.7f;
    double b = 0.7; 
    printf("%d %d %d",a<b,a>b,a==b);
    return 0;
 }  

I am getting 1 0 0 as output

and for

#include<stdio.h>
int main()  
{    
    float a = 1.7f;
    double b = 1.7; 
    printf("%d %d %d",a<b,a>b,a==b);
    return 0;
 }  

I am getting 0 1 0 as output.

Please tell me why I am getting these weird output and is there any way to predict these outputs on the same processor. Also how comparison is done of two variables in C ?

like image 787
Chetan Sharma Avatar asked Dec 22 '22 22:12

Chetan Sharma


1 Answers

It has to do with the way the internal representation of floats and doubles are in the computer. Computers store numbers in binary which is base 2. Base 10 numbers when stored in binary may have repeating digits and the "exact" value stored in the computer is not the same.

When you compare floats, it's common to use an epsilon to denote a small change in values. For example:

float epsilon = 0.000000001;
float a = 0.7;
double b = 0.7;

if (abs(a - b) < epsilon)
  // they are close enough to be equal.
like image 168
Starkey Avatar answered Jan 07 '23 02:01

Starkey