From: Christopher Phillips (shrydar_at_jaruth.com)
Date: 2004-12-11 12:19:59
On 10 Dec 2004, at 04:19, Jim Brain wrote:
> void calc (unsigned int old, unsigned int new) {
> unsigned int tmp;
> if(new < old) {
> tmp=old-new;
> } else {
> tmp=new-old;
> }
> if(tmp < 7000) {
> ...
> }
> }
>
> Is the old code...
>
> void calc (unsigned int old, unsigned int new) {
> int tmp;
> tmp=new-old;
/* any decent compiler will warn you of an implicit cast from unsigned
to signed at this point! */
> if(tmp > -7000 && tmp < 7000) {
> ...
> }
> }
Assuming 16 bit ints represented as 2s-complement, those two bits of
code will give the same result unless abs(new-old)>65536-7000, in which
case the second code snippet will run the stuff inside the if and the
old code won't. (for example, new=65530, old=20)
Doing the comparison before the subtraction effectively lets you work
to 17 bit precision. I have't been following the rest of the thread,
so I don't know how likely it is that new will differ from old by more
than 58536.
How precise is the 7000? You could always change the new code to
tmp=new/2-old/2
and compare to 3500 instead - that would avoid the problem with large
jumps getting lost.
Christopher.
Message was sent through the cbm-hackers mailing list
Archive generated by hypermail pre-2.1.8.