pythonsympytaylor-series

Taylorseries of ln(1 + x) with Sympy


I was trying to make a function, which computes the taylorseries of ln(1 + x), which takes a z argument (the value of x) and a k argument (till which term it should compute).

When I checked the function (with some prints) it goes wrong in the third term as it gives 2/3 instead of 1/3. I've computed it on my calculator and it should go right, but I think I'm missing something. I hope I can be helped further!

Taylorseries of ln(1 + x)

Code:

# !{sys.executable} -m pip install sympy
import math
from sympy import *

from sympy import diff, sin, exp 
from sympy.abc import x,y 


def sum_deff_ln(z , k):
    expr = ln(1 + x)
    g = 0
    for aantal in range(g, k, 1):
        if aantal == 0:
            getal = diff(expr,x)
            q = g + 1 
            subantwoord = lambdify(x, getal)
            antwoord = subantwoord((g))*z**(q)
        elif aantal == 1:
            getal = diff(getal,x)
            print(getal)
            subantwoord = lambdify(x, getal)
            q += 1
            antwoord = antwoord + (subantwoord((g))/q)*z**(q)
            print(antwoord)
        else:
            getal = diff(getal,x)
            subantwoord = lambdify(x, getal)
            print(getal)
            q += 1
            antwoord = antwoord + (subantwoord((g))/q)*z**(q)
            print(antwoord)
        if aantal == k-1:
            print(antwoord)
            
sum_deff_ln(1, 3)

Output:

-1/(x + 1)**2
0.5
2/(x + 1)**3
3
1.1666666666666665
1.1666666666666665

Solution

  • Can be simplified as (without any packages):

    def approx_ln(z,k):
        antwoord = 0
        for i in range(1 , k+1):
            subantwoord = ((-1)**(i+1) / i) * z**i
            antwoord += subantwoord
        return antwoord