ValueError: x, y, and format string must not be None 泰勒正弦

问题描述

我将要使用 tayloreries 来近似正弦并绘制与真实正弦比较的不同迭代。有人知道我哪里出错了吗?

%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,它返回 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)

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...