[Courses] [C] Debugging (Re: help me find my C bug? (long))
Conor Daly
conor.daly at oceanfree.net
Thu Jul 18 04:02:54 EST 2002
Arrgh!
I was just looking over these posts and realised that I have given the
"sign=" lines wrongly. The correct version is:
sign = sqrt (amount * amount) / amount;
This will produce +1 for positive numbers and -1 for negative.
On Wed, Jul 10, 2002 at 12:56:03PM +0000 or so it is rumoured hereabouts,
Conor Daly thought:
>
> On the matter of floating point imprecision, we run a database of weather
> records here and record quite a bit of stuff to one place of decimals.
> However, at times, a search for "rain=3.3" returns no data while "rain >3.29
> and rain <3.31" will return hundreds of lines!
>
> Using
>
> total=(amount * 100) + 0.5;
>
> works, but to cope with negative numbers you need just a little more. You
> can use two (probably more) different approaches;
>
> 1. if else
>
> if ( amount < 0 ) {
> total=(int) (amount * 100) - 0.5);
> } else {
> total=(int) (amount * 100) + 0.5);
> }
>
> 2. use the sign
>
> sign = sqrt (amount * amount);
sign = sqrt (amount * amount) / amount;
> total=(int) (amount * 100) + (sign * 0.5);
>
> note that either of these methods give rise to an inconsistency where -0.5
> rounds to 0 while -1.5 rounds to -2 and -1 gets missed along the way. The
> solution to this (IMO!) is to use just a *little* extra for the rounding
> figure. ie.
>
> 1. if else
>
> if ( amount < 0 ) {
> total=(int) (amount * 100) - 0.50001);
> } else {
> total=(int) (amount * 100) + 0.5);
> }
>
> 2. use the sign
>
> sign = sqrt (amount * amount);
sign = sqrt (amount * amount) / amount;
> total=(int) (amount * 100) + (sign * 0.50001);
>
> This will produce expected behaviour but ONLY so long as the "little bit
> extra" is well below the precision of the numbers you are rounding.
>
> Conor (rambling...)
Conor
--
Conor Daly <conor.daly at oceanfree.net>
Domestic Sysadmin :-)
---------------------
Faenor.cod.ie
4:10am up 55 days, 13:27, 0 users, load average: 0.23, 0.08, 0.04
Hobbiton.cod.ie
3:59am up 29 days, 3:21, 1 user, load average: 0.00, 0.00, 0.00
More information about the Courses
mailing list