Message from discussion Equality failure in <=.
From: Seebs <usenet-nos...@seebs.net>
Subject: Re: Equality failure in <=.
User-Agent: slrn/0.9.8.1 (NetBSD)
Date: 24 Mar 2010 22:12:12 GMT
Organization: Megabitz - More USENET, Faster USENET
NNTP-Posting-Date: 24 Mar 2010 22:12:12 GMT
On 2010-03-24, Robbie Hatley <see.my.signat...@for.my.contact.info> wrote:
> Oh, and I see another bug in the output of my
> celsius-to-fahrenheit converer program, that I posted about
> here a few minutes ago (re. extra blank lines form printf).
No, you don't. :)
> for (Cels = CelsMin; Cels <= CelsMax; Cels += CelsInc)
> Fahr = (((Cels*180.0)/100.0)+32);
> printf("%10.3f %10.3f\n\n", Cels, Fahr);
> 41.000 105.800
> Looks like the <= comparison is failing when Cels gets up to 41.000.
> I'm guessing it's somehow gets off a very small amount. Perhaps
> it's 41.00000001 when it gets compared to 41, so <= return false.
> I could change "Cels <= CelsMax" to "Cels <= (CelsMax+0.0001)".
> But that's a bit ugly. Any simpler way to do this?
It's surprisingly hard. Basically, floating point numbers generally
can't represent values that aren't exact multiples of a power of two.
"0.2" is not exact, so addition of "0.2" repeatedly is also not exact.
If you really need to do this, do all the loop controls in integer math,
then convert at the last minute using a fixed scale factor. e.g.,
loop up to 205, then divide by 5 inside the loop.
Copyright 2010, all wrongs reversed. Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!