Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!mnetor!seismo!rutgers!princeton!allegra!alice!ark
From: ark@alice.UUCP
Newsgroups: comp.lang.c,comp.unix.xenix
Subject: Re: Are the floating point routines on my machine broken?
Message-ID: <6506@alice.uUCp>
Date: Wed, 31-Dec-86 12:21:47 EST
Article-I.D.: alice.6506
Posted: Wed Dec 31 12:21:47 1986
Date-Received: Thu, 1-Jan-87 05:40:49 EST
References: <442@catnip.UUCP>
Organization: AT&T Bell Laboratories, Liberty Corner NJ
Lines: 42
Xref: mnetor comp.lang.c:569 comp.unix.xenix:35

In article <442@catnip.UUCP>, ben@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.