floating points not exact in C- example

chris (2008-11-08 00:40:54)
502 views
0 replies
A friend pointed this out to me today and now I'm scratching my head. The code initialises a value to zero, then increments by 0.1 10 times. The end result does not equal to 1. I guess you can't assume a floating point value to be exact. If I cast val to int before running the comparison, of course the test returns true, because that would lop off any training points, leaving exactly 1:

secondhalf-lm:junk clacy$ cat adder.c  && gcc adder.c -o foo && ./foo 
#include <stdio.h>
#include <stdlib.h>


int main ( int argc, char *argv[] ){
	float val = 0;
	int i = 0;

	while(i<10){
		val += 0.1;
		i++;
	}

	printf("\nval is now %f\n",val);

	if(1 == val){
		printf("\nThat is equal to 1\n");
	}else{
		printf("\nThat is not equal to 1\n");
	}

	return 0;
}

val is now 1.000000

That is not equal to 1


christo
comment