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

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

我即将用泰勒级数逼近正弦并绘制不同的迭代以与真实正弦进行比较。有人知道我哪里弄错了吗?

%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))

你的缩进有误,return(sinx)else 里面 - 对于 n==1 它 returns None

所以改变缩进

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)

或为 n==1

添加 return(sinx)
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)