绘制用 Python 编写的级数函数

问题描述 投票:0回答:1

我想使用 Matplotlib 和 Numpy 数组在 python 中绘制一个函数。我使用 200 个 x 值。功能:

这是一个 n 阶傅里叶级数,但这并不重要。我有一些代码,但根据 Desmos 的说法,它生成的曲线是错误的。它应该看起来像这样。

这是我的代码:


def fourier(values,order):
    S=np.zeros(200)
    for i in range(1,order):
        s=(4/np.pi)*(1/((2*i)+1))*(np.sin(((2*i)-1)*2*np.pi*values))
        S=np.add(S,s)
    return S
        

plt.plot(xpoints,fourier(xpoints,33))```
python math plot graph physics
1个回答
0
投票

您正在函数范围之外进行绘图。请注意,我在

R
中预先计算了 2m-1 作为一个小优化。

import numpy as np
import matplotlib.pyplot as plt

def fourier(values,order):
    S=np.zeros(200)
    R = np.array(range(order)) * 2 + 1
    for i,v in enumerate(values):
        s = 4/np.pi * np.sum(np.sin(R*2*np.pi*v)/R)
        S[i] = s
    return S
        

xpoints = np.array(range(200))/100
plt.plot(xpoints,fourier(xpoints,33))
plt.show()

输出:

© www.soinside.com 2019 - 2024. All rights reserved.