Search code examples
algorithmmath

Given the exp() function, how to implement the ln() function?


P.S. exp() is the function y = e^x and ln() is y = ln(x)


Solution

  • You can find the value in log time by binary searching the answer. This is possible because log X is a monotonically increasing function.

    (courtesy of WolframAlpha).

    For example, if the value whose logarithm we have to calculate (assume it to be X) is greater than 1, then start with an assumption of answer = X. Raise the power e^answer and check if the value is greater than or smaller than X. Now based on whether the value you get is greater than or lesser than X, you can refine your limits. The search stops when you have reached within suitable ranges of your answer.

    double log(double X){
            double lo = 1;
            double hi = X;
    
            while(true){
                double mid = (lo+hi)/2;
                double val = power(e, mid);
                if(val > X){
                    hi = mid;
                }
                if(val < X){
                    lo = mid;
                }
                if(abs(val-X) < error){
                    return mid;
                }
            }
        }
    

    Similarly, if the value of X is smaller than 1, then you can reduce this case to the case we have already considered, ie. when X is greater than 1. For example if X = 0.04, then

    log 0.04 = log (4/100) = (log 4) - (log 100)