Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.misc -> Re: Accuracy of the log function

Re: Accuracy of the log function

From: Connor McDonald <connor_mcdonald_at_yahoo.com>
Date: Wed, 29 Aug 2001 18:40:54 +0100
Message-ID: <3B8D2926.44C2@yahoo.com>


O.K.Man wrote:
>
> Dear all,
>
> I've tried to write a function to determine the number of bits of an
> integer, the implementation is like this:
>
> FUNCTION bit_cnt
> (pi_number NUMBER
> ) RETURN NUMBER IS
> BEGIN
> IF pi_number > 0 THEN
> RETURN TRUNC(LOG(2,pi_number)) + 1;
> ELSE
> RETURN 1;
> END IF;
> END bit_cnt;
>
> However, I found that the function return wrong result if the number is the
> power of 2 (i.e. 2, 4, 8, 16, 32, etc) and then discovered that the values
> returned by the LOG function on these values are actually 0.99999...,
> 1.99999..., 2.99999..., 3.9999..., 4.9999... etc. After the TRUNC function,
> the values returned by my function are 1, 2, 3, 4, 5, etc and obviously are
> wrong.
>
> I believe that replacing the TRUNC by ROUND, FLOOR or CEIL will not solve
> the problem.
>
> And I finally modified the function like this
>
> FUNCTION bit_cnt
> (pi_number NUMBER
> ) RETURN NUMBER IS
> vl_bit NUMBER;
> BEGIN
> IF pi_number > 0 THEN
> vl_bit := TRUNC(LOG(2,pi_number)) + 1;
> -- counter check the result
> IF POWER(2,vl_bit) <= pi_number THEN
> vl_bit := vl_bit + 1;
> END IF;
> RETURN vl_bit;
> ELSE
> RETURN 1;
> END IF;
> END bit_cnt;
>
> My question is that can we consider the behaviour of the LOG function as a
> bug ? Is there a better way to implement my function ?
>
> Best regards,
>
> O.K.Man

If you round to (say) the nearest 20th decimal place, then you should get the answers you're after.

hth
connor

-- 
==============================
Connor McDonald

http://www.oracledba.co.uk

"Some days you're the pigeon, some days you're the statue..."
Received on Wed Aug 29 2001 - 12:40:54 CDT

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US