c++mathoutputnatural-logarithm

C++ program which calculates ln for a given variable x without using any ready functions


I've searched for the equation which calculates the ln of a number x and found out that this equation is:

enter image description here

and I've written this code to implement it:

double ln = x-1 ;
    for(int i=2;i<=5;i++)
    {
        double tmp = 1 ;
        for(int j=1;j<=i;j++)
            tmp *= (x-1) ;
        if(i%2==0)
            ln -= (tmp/i) ;
        else
            ln += (tmp/i) ;
    }
    cout << "ln: " << setprecision(10) << ln << endl ;

but unfortunately I'm getting outputs completely different from output on my calculator especially for large numbers, can anyone tell me where is the problem ?


Solution

  • The equation you link to is an infinite series as implied by the ellipsis following the main part of the equation and as indicated more explicitly by the previous formulation on the same page:

    enter image description here

    In your case, you are only computing the first four terms. Later terms will add small refinements to the result to come closer to the actual value, but ultimately to compute all infinite steps will require infinite time.

    However, what you can do is approximate your response to something like:

    double ln(double x) {
      // validate 0 < x < 2
      double threshold = 1e-5;  // set this to whatever threshold you want
      double base = x-1;        // Base of the numerator; exponent will be explicit
      int den = 1;              // Denominator of the nth term
      int sign = 1;             // Used to swap the sign of each term
      double term = base;       // First term
      double prev = 0;          // Previous sum
      double result = term;     // Kick it off
    
      while (fabs(prev - result) > threshold) {
          den++;
          sign *=- 1;
          term *= base;
          prev = result;
          result += sign * term / den;
      }
    
      return result;
    }
    

    Caution: I haven't actually tested this so it may need some tweaking.

    What this does is compute each term until the absolute difference between two consecutive terms is less than some threshold you establish.

    Now this is not a particularly efficient way to do this. It's better to work with the functions the language you're using (in this case C++) provides to compute the natural log (which another poster has, I believe already shown to you). But there may be some value in trying this for yourself to see how it works.

    Also, as barak manos notes below, this Taylor series only converges on the range (0, 2), so you will need to validate the value of x lies in that range before trying to run actual computation.