Subject: Re: Unexpected "double" behaviour
To: None <netbsd-help@netbsd.org>
From: Matthias Pfaller <leo@marco.de>
List: netbsd-help
Date: 09/26/2001 13:47:39
In article <04ae01c1465b$f4157620$1c22a8c0@matthewf.cat.co.za>,
	matthewf@cat.co.za (Matthew Fincham) writes:
> Hello
> 
> I am seeing some unexpected behaviour when casting a double to an int, and
> was wondering if there is an explanation for it. The following program shows
> the problem:
> 
> 1> int main()
> 2> {
> 3> double d;
> 4> int i;
> 5>
> 6> d=(double)4.52;

Just check the binary representation for 0.452:
	bash$ bc -l
	obase=2
	.4520000000000000000
	.0111001110110110010001011010000111001010110000001000001100010010

Now convert the binary fraction back to decimal:

	bash$ bc -l
	ibase=2
	.0111001110110110010001011010000111001010110000001000001100010010
	.4519999999999999999765812330743131042254390195012092590332031250

As you can see, the result is not 0.452... There is no exact binary
representation for 0.452. As all floatingpoint values are stored as
fraction and an exponent, (double)452 has no exact binary representation
as well.

Regards, Matthias
-- 
Matthias Pfaller                            Software Entwicklung
marco Systemanalyse und Entwicklung GmbH    Tel   +49 8131 5161-41
Hans-Böckler-Str. 2, D 85221 Dachau         Fax   +49 8131 5161-66
http://www.marco.de/                        Email leo@dachau.marco.de