c++algorithmtaylor-series

Finding the Natural Logarithm of a number using Taylor Series in C++


The specific question

Okay so I have spent the last 2 hours working on this, tweaked the code a hundred times, but I got nothing. No errors and no warnings, but the answer is wrong. Here is my code:

#include <iostream>
using namespace std;

void main()
{
    /***********Variable Declarations************/

    double count = 1, totalValue = 0, it, x, z=1, powe = 1, y;

    cout << "Iterations=";
    cin >> it;
    cout << "x=";
    cin >> x;
    /***************End User Input***************/

    while (count <= it)
    {
        for (int i = 0; i < powe; i++) {
            z *= (x - 1) / (x + 1);
        }
        y = (1 / powe)*z;

        totalValue = totalValue + y;
        powe = powe + 2;
        count++;
    }

    cout << "The Result is:" << 2*totalValue << endl;
}

I know it is a problem of logic (math), but I can't seem to find it. Thank you.

Edit: We are not allowed to use any other library.


Solution

  • You forgot to set z to 1 in each iteration of your while:

    #include <iostream>
    using namespace std;
    
    
    void main()
    {
    /***********Variable Declarations************/
    
    double count = 1, totalValue = 0, it, x, z=1, powe = 1, y;
    
    cout << "Iterations=";
    cin >> it;
    cout << "x=";
    cin >> x;
    /***************End User Input***************/
    
    
    
    while (count <= it)
    {
    
        for (int i = 0; i < powe; i++) {
            z *= (x - 1) / (x + 1);
        }
        y = (1 / powe)*z;
    
        totalValue = totalValue + y;
        powe = powe + 2;
        count++;
        z = 1; //Without this line you will have very high powers
    }
    
    cout << "The Result is:" << 2*totalValue << endl;
    
    }
    

    EDIT:

    You can optimize your approach, by not having to calculate the power from scratch all the time:

    #include <iostream>
    using namespace std;
    
    
    void main()
    {
    /***********Variable Declarations************/
    
    double count = 1, totalValue = 0, it, x, z, powe = 1, y;
    
    cout << "Iterations=";
    cin >> it;
    cout << "x=";
    cin >> x;
    z = (x + 1) / (x - 1); //We start from power -1, to make sure we get the right power in each iteration;
    //Store step to not have to calculate it each time
    double step = ((x - 1) * (x - 1)) / ((x + 1) * (x + 1));
    /***************End User Input***************/
    
    
    
    while (count <= it)
    {
    
        z * = step;
        y = (1 / powe)*z;
    
        totalValue = totalValue + y;
        powe = powe + 2;
        count++;
        //We no longer need to set z to 1, as the previous value becomes useful
    }
    
    cout << "The Result is:" << 2*totalValue << endl;
    
    }