[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: deviating results
From: |
Ulrich Eckhardt |
Subject: |
Re: deviating results |
Date: |
Tue, 06 Sep 2005 22:35:20 +0200 |
User-agent: |
KNode/0.8.2 |
Christian Christmann wrote:
> this is my function which I'm using to determine the bit width of
> a given value.
>
> int getBWidth( long long constValue )
> {
> int bWidth = 0;
> for ( int n = 64; n >= 1; n-- )
> if ( ( constValue >= -pow( (float) 2, n - 1 ) ) &&
> ( constValue <= pow( (float) 2, n - 1 ) - 1 ) )
> bWidth = n;
> else
> return bWidth;
> return bWidth;
> }
I'm not really sure I understand what you're doing there, but I think you
should replace the pow() call with bit-shifting. If you need it fast, you
could even use a plain if-else tree. Also, isn't the value of bWidth
always equal to n+1? Furthermore, what if long long is larger than 64
bits? IIRC, it has to be 64 bits, although you're technically relying on
C99 then, which is not part of C++.
> This function works fine for small arguments. But for larger
> long long values the results deviate, e.g.
> passing 4294967295 ( 2^32 - 1 ) as signed long long argument should
> result in a return value of bWidth=33 while argument 4294967296 should
> return the value 34.
> However, the function returns for both values the value 34. After playing
> around with some function arguments I figured out that the threshold
> among 33 and 34 bits is the value 4294967168.
>
> So, my question is where the deviation between 4294967296 and
> 4294967168 comes from?
Floating point math is not 100% precise.
Uli
--
http://gcc.gnu.org/faq.html
http://parashift.com/c++-faq-lite/
- deviating results, Christian Christmann, 2005/09/06
- Re: deviating results,
Ulrich Eckhardt <=