Problems coding a Taylor series (natural logarithm)

1

I have a small problem with the Taylor series. To be exact with the natural logarithm. For what I realized, is because the divisor grows brutally and the word script does not give me more, I've tried with data types long long but even so it helps me solve the problem.

C ++ Code:

#include <bits/stdc++.h>
using namespace std;

double log_mac(double);

int main()
{
    double x = 10;
    cout << "Ln calculado con la funcion en <cmath>" << endl
    << "ln(10) = " << log(x) << endl;

    cout << "Ln calculado con funcion propia" << endl;
    cout << "ln(10) = " << log_mac(x) << endl;
}
double log_mac(double x)
{
    double resp = 0;

    for(int n = 1 ; n <= x ; n++)
    {
        double dividendo = pow(-1, n+1);
        double divisor = n;
        double multiplicador = pow(x, n);
        double temp = (dividendo / divisor) * multiplicador;

        //cout << dividendo << endl;

        resp += temp;
    }
    return resp;
}
    
asked by Alex 21.05.2017 в 20:25
source

1 answer

1

According to the function

On wikipedia.

It can be calculated in the following way for values 0 < x < 2 :

#include <iostream>
#include <math.h>
using namespace std;

double log_mac(double);

int main()
{
    double x = 0.2;
    cout << "Ln calculado con la funcion en <cmath>" << endl
    << "ln(10) = " << log(x) << endl;

    cout << "Ln calculado con funcion propia" << endl;
    cout << "ln(10) = " << log_mac(x) << endl;
}

double log_mac(double x){
    double resp = 0;
    int iteraciones = 10;

    for(int n = 1 ; n <= iteraciones ; n++){
        resp += pow(-1, n + 1) * pow(x - 1.0, n) / n;
    }

    return resp;
}

Out of the range I mentioned before, the approach becomes useless:

You can see the following useful links.

answered by 22.05.2017 в 01:38