Log In  

Logarithm Benchmark

Cart #log_bench-0 | 2023-06-02 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA

Logarithm algorithms

wiki method

stats

tokens:46

description

the wiki method uses an interesting property of logarithms to compute a value. specifically:
log(A * B) = log(A) + log(B)
by using a look up table for all the logarithms (base 10 of course) of the first 9 digits (1-9) we can use the following code to compute logarithms:

log10_table = {
 0, 0.3, 0.475,
 0.6, 0.7, 0.775,
 0.8375, 0.9, 0.95, 1
}

function log10(n)
 if (n < 1) return nil
 local t = 0
 while n > 10 do
  n /= 10
  t += 1
 end
 return log10_table[flr(n)] + t
end

what this algorithm actually does is repeatedly divide by 10 and add the number of times it does this to a counter. Essentially we are assuming the number n can be expressed as m * 10 *10 *10... and we are simply removing these tens. then re-adding them in at the end.

extended wiki method

stats

tokens:98 (can probably be improved easily)

description

its the same thing but we use the following properties to extend the domain of the function:
log base n of m = log base 10 of n / log base 10 of m
log(n)=log(A)-log(A/n) when 0 < n < 1

my method

stats

tokens:118

description

I simply test 'all' the possible digits and calculate the error. then take the digit with the lowest error then I move on to test the next digit. Effectivly a brute force method.
The code:

function log(n,m)
 assert(n>0and m>0and m!=1)
 if(m<1)return log(n,10)/log(m,10)
 if(n<1)return -log(1/n,m)
 local g,cur,err='0000.0000',g,9999
 for i=1,9do
  if i!=5then
   for j=0,9do
    cur=sub(g,1,i-1)..j..sub(g,i+1)
    local c=m^tonum(cur)-n
    if abs(c)< err and c<=0then
     g,err=cur,abs(c)
    end
   end
  end
 end
 return tonum(g)
end
P#130462 2023-06-02 15:49


[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-18 01:52:07 | 0.009s | Q:14