Search code examples
pythonnumpymatplotlibmathtaylor-series

ValueError: x, y, and format string must not be None taylor sine


I'm about to approximate sine with a taylorseries and plot different iterations in comparrison with the real sine. Does anybody know where i made a mistake?

%pylab inline
from math import factorial as fak

def taylor_sinus(n,x):
    if n==1:
        sinx=x
    elif n < 1:
        print('ERROR 302: approximation not found')
    else:
        sinx=0
        for i in range(1,n):
            sinx=sinx-((-1)**i*((x**(2*i-1))/fak(2*i-1)))
        return(sinx)


x=np.linspace((-2*pi), (2*pi), 100)
iterations=(1,3,8,11,)

for iteration in (iterations):
    plt.plot(x, taylor_sinus(iteration,x), label='Iterationen: {0}'.format(iteration))
plt.plot(x, sin(x), ':', lw=4, label='The one and only Sinus')

plt.legend(bbox_to_anchor=(1, 1))
plt.xlabel('x')
plt.ylabel('f(x)')
plt.ylim(-2,2)
plt.grid()
plt.figure(figsize=(20,10))

Solution

  • You have wrong indentation and return(sinx) is inside else - and for n==1 it returns None

    So change indentation

    def taylor_sinus(n,x):
        if n==1:
            sinx=x
        elif n < 1:
            print('ERROR 302: approximation not found')
        else:
            sinx=0
            for i in range(1,n):
                sinx=sinx-((-1)**i*((x**(2*i-1))/fak(2*i-1)))
        return(sinx)
    

    or add return(sinx) for n==1

    def taylor_sinus(n,x):
        if n==1:
            sinx=x
            return(sinx)
        elif n < 1:
            print('ERROR 302: approximation not found')
        else:
            sinx=0
            for i in range(1,n):
                sinx=sinx-((-1)**i*((x**(2*i-1))/fak(2*i-1)))
            return(sinx)