Are the floating point routines on my machine broken?

ark at alice.UUCP ark at alice.UUCP
Thu Jan 1 03:21:47 AEST 1987


In article <442 at catnip.UUCP>, ben at catnip.UUCP writes:
> 
> I have noticed what I believe is incorrect behavior on the part of the
> floating point routines on my machine.

[he includes a sample program that increments a variable, initially 0,
by 0.2 until it passes 3; then prints the variable minus 3]

> When this program is run, it produces:
> 0.000000
> 0.200000

	[and so on]

> 2.600000
> 2.800000
> Final value: 3.000000 less 3 is 4.440892e-16
> 
> It seems to be going through the loop one time less than I expected.
> I don't understand this behavior.  3.0 can certainly be represented
> precisely in binary, so only the .2 should subject to roundoff error.
> The crazy thing is, it appears that the floating point routines are
> rounding this number up instead of down!  It is the only explanation
> I can think of to explain this output.  Is roundup considered acceptable
> behavior for floating point routines?  Or am I somehow misinterpreting
> the problem?

You're not misinterpreting it very much.

You are quite right: 0.2 cannot be represented exactly in floating-point.
So what number you get is determined by the exact characteristics of
your system.  You will probably get one of the two nearest representable
numbers; from your results it looks like you are getting the one slightly
larger.  Thus as you add multiple instances of that value to 0, you tend
to get numbers that are slightly larger than multiples of 0.2  When
you think you're at 3, you're really at 3 plus a small number.

This might be easier to understand if you print the value of

	(0.2 * 5) - 1

This "should" be zero, but it won't.



More information about the Comp.lang.c mailing list