Is .2 irrational?

Gary M. Samuelson garys at bunker.UUCP
Thu Jan 8 00:48:55 AEST 1987


In article <153 at piaget.UUCP> jc at piaget.UUCP (John Cornelius, System Manager) writes:
>The value .2 is an irrational fraction in binary.

Imprecise, at best.  The number .2 (also represented as 2/10) is
rational, regardless of the form in which it is expressed.  The
problem is that it is not possible to represent exactly that particular
number in typical floating point formats.  A floating point format could
be designed which allowed exact representation of all decimal fractions,
up to some number of places precision, but I know of no implementation
which does that.  (If there were, how would that affect program
portability?)

>Adding the
>representation of (irrational) .2 to (rational) +3. results in a
>number slightly higher than (rational) +3.0, thereby terminating
>the loop.

Adding .2 to 3. should yield something significantly higher
than 3.0 -- approximately 3.2, in fact.

>Henry Spencer is quite right about using floating point numbers
>as loop indices, it is a _bad_ practice and has been for nearly
>30 years.

Well, you just have to do the comparison right.  I remember being
taught never to test two floating point numbers for equality, but
to take the absolute value of the difference and see if it was
less than some epsilon, which was determined by how precise you
wanted to be (or could be).  In fact, in Basic-plus (RSTS/e) there
was an operator which meant "is approximately" (defined as appearing
the same when printed in the standard format).  Very useful, I
thought.

Gary Samuelson



More information about the Comp.lang.c mailing list