delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/01/06/12:25:36

From: Hans-Bernhard Broeker <broeker AT acp3bf DOT physik DOT rwth-aachen DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: DJGPP BUG!!!!!!! ???
Date: 6 Jan 2000 12:47:30 GMT
Organization: Aachen University of Technology (RWTH)
Lines: 46
Message-ID: <8522t2$bqj$1@nets3.rz.RWTH-Aachen.DE>
References: <851o9m$h4t$1 AT news DOT lth DOT se>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 947162850 12115 137.226.32.75 (6 Jan 2000 12:47:30 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 6 Jan 2000 12:47:30 GMT
User-Agent: tin/1.4-19991113 ("No Labels") (UNIX) (Linux/2.0.0 (i586))
Originator: broeker@
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Niklas Pettersson <npedt97 AT student DOT vxu DOT se> wrote:

> I think I have found an error in DJGPP... 

You haven't. The error is in your expectation of what this program's
output should be.

>  for ( double i = 0; i < 2.1; i += 0.1 )
>    {
>     cout << "Double:" << i << ", Integer:" << int(i) << endl;
>    }

> but 1.0 gets converted to 0!!!!

Yes, it does. You ask why? The problem is a typical problem of 
newbies digging their way into floating point variables: you
expect that if you write 0.1, the program will use exactly that
number, i.e 0.100000000000000000000... 

Fact is, computers can't store numbers to infinite precision, so the
computer has to round this to some close approximation, wich will
usually be something like

	0.99999999999

(with a finite number of '9' digits). It's not 0.1 because the CPU is
using binary numbers, and 0.1 is not representable by a finite binary
fractional number. 

If you raise the number of printed digits for your display of the
double variable, you'll see this. Or you can output (i-1.0) to see
that i is actually not exactly 1.0, even though your loop made you
think so.

If printed, this value is rounded to a fixed number of digits, but if
you cast it to integer, it will be *cut* to the highest integer not
larger than the value itself.  For 0.99999999, that integer is 0, not
1, as you expected it to be.

To sum it up, remember this old saying:

	In computing, 10.0 times 0.1 is hardly ever 1.0

-- 
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019