Search code examples
c++loopsmathlogarithm

Program that calculates the value of natural logarithm of 2


I'm trying to write a program that reads in from the user the number of terms to be used in calculating the natural logarithm of 2. EX: Log(2) with 5 terms is 1/1 - 1/2 + 1/3 - 1/4 + 1/5. The denominator is increased by 1 with each subsequent term, and addition and subtraction signs alternate between each term. I just can't seem to find the right loop setup to make this work correctly. Any help would be appreciated.


Solution

  • Use a multiplication factor that toggles from +1 to -1 and then to +1 again as you iterate, then multiply your current 1/n term by that.

    double ln2(int terms) {
    
        double sign = 1.0
        double log = 0.0;
    
        for (double n = 1; n <= terms; n += 1.0) {
            // calculate your 1/n term here
            log += sign / n;    // == sign * 1.0 / n
    
            // and reverse polarity for the next iteration
            sign = -sign;
        }
    
        return log;
    }
    

    NB: this series converges very slowly!