Originally Posted by

**j.sreejit**
Please consider the following code

Code:

float a = 0.7;
if(a <= 0.7)
printf("Less or equal");
else
printf("Greater");

Kindly explain. Thank you in advance.

You must check that the floating point is accurate to within a certain tolerance, i.e. plus or minus a very small value away from the value you are comparing with must be considered acceptably 'equal'.

Try this program. It takes a bunch of positive floating point numbers and then multiplies by 10 (or whatever you pass in as the first program argument), does the same operation with negative versions of the values and then shows the difference between the result and the value expected when assigned from a constant. When the multiplier is 10 the difference mathematically would be zero but some values will be slightly inaccurate. Different values will be inaccurate by different amounts on different platforms.

Code:

#include <stdio.h>
#include <stdlib.h>
/*
Show how fractional decimal values cannot be stored in finite number
of binary digits
*/
int main(int argc, char ** argv)
{
double pos, neg, pdiff, ndiff;
int f = 10;
int i;
double r;
double cpos[10] = { /* constants representing expected results */
11.0,
22.0,
33.0,
44.0,
55.0,
66.0,
77.0,
88.0,
99.0,
110.0
};
double cneg[10] = { /* constants representing expected results */
-11.0,
-22.0,
-33.0,
-44.0,
-55.0,
-66.0,
-77.0,
-88.0,
-99.0,
-110.0
};
if (argc > 1)
{
f = atoi(argv[1]);
}
printf("\t%10s %10s %10s %10s %10s\n", "i", "pos", "diff", "neg", "diff");
pos = 0.0;
for (i = 0; i < 10; i++)
{
pos += 1.1; /* a range of positive decimal fractions */
r = pos * f; /* simple multiplication by 10 */
pdiff = cpos[i] - r; /* is result different from constant */
neg = -pos; /* a range of negative decimal fractions */
r = neg * f; /* simple multiplication by 10 */
ndiff = cneg[i] - r; /* is result different from constant */
printf("\t");
printf("%10d ", i);
printf("%10.2g ", pos);
printf("%10.2g ", pdiff);
printf("%10.2g ", neg);
printf("%10.2g ", ndiff);
printf("\n");
}
return 0;
}