floating points not exact in C- example

chris (2008-11-08 00:40:54)
2065 views
0 replies
The code initialises a value to zero, then increments by 0.1 10 times. The end result does not equal to 1, demonstrating that 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 %fn",val);

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

	return 0;
}

val is now 1.000000

That is not equal to 1


christo
comment