【问题标题】:ValueError: x, y, and format string must not be None taylor sineValueError:x、y 和格式字符串不得为 None 泰勒正弦
【发布时间】:2021-04-10 10:21:04
【问题描述】:

我将用泰勒序列近似正弦,并绘制不同的迭代以与真正的正弦进行比较。有谁知道我哪里出错了?

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

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。那里有有用的信息。
  • 你可能有错误的缩进并且return(sinx)else里面——所以对于n==1它返回None——这使得显​​示它有问题并且你得到你的错误消息。跨度>

标签: python numpy matplotlib math taylor-series


【解决方案1】:

您的缩进错误,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)

或为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)

【讨论】:

    猜你喜欢
    • 2022-07-03
    • 1970-01-01
    • 2017-12-02
    • 2014-02-17
    • 2017-04-10
    • 1970-01-01
    • 2021-07-10
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多