Search code examples
clogarithmmath.htaylor-series

Problem with Taylor Series implementation of logarithm


I tried to make a function output of which approximates the value of logarithm of x (x is a floating number) using the Taylor expansion.

Taylor series of natural logarithm:

ln(x) = {n=0 (sigma) inf} (-1)^n*(x-1)^(n+1)/(n+1)

(used the sigma summation) for a clearer image of Taylor expansion, see https://en.wikipedia.org/wiki/Taylor_series#First_example

Furthermore: log(a,b)=log(a)/log(b) (a is the base)

Below is my implementation using these principle:

double logtaylor(double a,double b,double prec)
{
    double suma=0,sumb=0,n;


    for(n=0;n<prec+1;++n)
    {
            suma+=(pow(-1,n)*pow(a-1,n+1)/(n+1));
            sumb+=(pow(-1,n)*pow(b-1,n+1)/(n+1));
            printf("%d)suma=%lf\n",(int)n,suma);
            printf("%d)sumb=%lf\n",(int)n,sumb);
    }


    return suma/sumb;
}

I was testing for log of 3 to base 2 -logtaylor(2,3,30)- at precision level 30.

Output:

math.h: 0.630930
0)suma=1.000000
0)sumb=2.000000
1)suma=0.500000
1)sumb=0.000000
2)suma=0.833333
...
26)suma=0.711323
26)sumb=3272620.000449
27)suma=0.675609
27)sumb=-6314360.570980
28)suma=0.710091
28)sumb=12198429.497986
29)suma=0.676758
29)sumb=-23592964.635348
30)suma=0.709016
30)sumb=45680701.429168

Both statements of summations a and b are exactly the same except the variables, however they behave completely different.suma, is fairly close to the real value -calculated in math header.I confirmed using a calc also (log(2,3)~0.63092975356)- whereas its counterpart is deviating enormously climbing to millions. I could not wrap my mind around it. I appreciate any help. Thanks in advance.


Solution

  • The domain of convergence of the Taylor series for ln is (0, 2]. Outside of this, the series will not converge to the value of ln x; it will grow in magnitude forever. In other words, you have a math problem, not a software problem—the software is correctly evaluating the series, but the Taylor series does not approximate ln x outside of 0 < x ≤ 2.