Inherent imprecision of floating point variables

Loren Petrich loren at tristan.llnl.gov
Sat Jul 14 11:08:51 AEST 1990


In article <b3f.2688bfce at ibmpcug.co.uk> dylan at ibmpcug.CO.UK (Matthew Farwell) writes:
>In article <44436 at ism780c.isc.com> marv at ism780.UUCP (Marvin Rubenstein) writes:
>Consider the code segment:-
>
>main()
>{
>	float f;
>
>	f = 0.0;
>	while (1) {
>		if (f == 10.0) break;
>		printf("%f\n", f);
>		f += 0.1;
>	}
>	printf("Stopped\n");
>}
>
>If its all to do with conversion routines, why doesn't this stop when f
>reaches 10?

	That is because 0.1 is not represented as a finite-length
number in binary. In binary form it is:

	0.0011001100110011...

	with an infinitely repeating sequence of digits.

	Check it out by multiplying it by 10 (binary: 1010).

	Since a computer will only use finite-length numbers, it will
cut off this infinite-length representation, and get a number that is
not quite 0.1. But no integer multiple of that can equal 10.0, so the
program gets stuck in an infinite loop. The moral: avoid this sort of
test. You won't get exact agreement.

						        ^    
Loren Petrich, the Master Blaster		     \  ^  /
	loren at sunlight.llnl.gov			      \ ^ /
One may need to route through any of:		       \^/
						<<<<<<<<+>>>>>>>>
	lll-lcc.llnl.gov			       /v\
	lll-crg.llnl.gov			      / v \
	star.stanford.edu			     /  v  \
						        v    
For example, use:
loren%sunlight.llnl.gov at star.stanford.edu

My sister is a Communist for Reagan



More information about the Comp.lang.c mailing list