Connecting Tech Pros Worldwide Forums | Help | Site Map

formula for logarithms to base two of a number

Member
 
Join Date: Apr 2007
Posts: 53
#1: Mar 16 '09
Is there a formula for finding logarithms to base two of a number.If so wtat is it.Thanks for any replying.

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,660
#2: Mar 17 '09

re: formula for logarithms to base two of a number


you mean if you don't have a calculator at hand that computes the logarithms?

there are some series you can use.
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#3: Mar 17 '09

re: formula for logarithms to base two of a number


There's a simple integer approximation:

Expand|Select|Wrap|Line Numbers
  1. int log2(unsigned int n) {
  2.   int log = 0;
  3.   if (n >= 1<<16) { n >>= 16; log += 16; }
  4.   if (n >= 1<< 8) { n >>=  8; log +=  8; }
  5.   if (n >= 1<< 4) { n >>=  4; log +=  4; }
  6.   if (n >= 1<< 2) { n >>=  2; log +=  2; }
  7.   if (n >= 1<< 1) {           log +=  1; }
  8.   return ((n == 0) ? -1 : log);
  9. }
  10.  
(this assumes C or C++ being used).

kind regards,

Jos
Member
 
Join Date: Apr 2007
Posts: 53
#4: Mar 22 '09

re: formula for logarithms to base two of a number


thanks for replying.really appreciate it
Reply


Similar Algorithms / Advanced Math bytes