三角傅立叶级数系数

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

我正在尝试在所需函数上绘制三角函数傅里叶级数,但我遇到了一些问题。

代码如下:

import numpy as np
import scipy as scp
import matplotlib.pyplot as plt


def desired_function(t):
    return t ** 2


def a_zero(function, half_period, inferior_limit, superior_limit):
    return (1/2*half_period) * scp.integrate.quad(function, inferior_limit, superior_limit)[0]


def a_k(function, x, k, half_period, inferior_limit, superior_limit):
    return (1/half_period) * scp.integrate.quad(function * np.cos(x * k * (np.pi / half_period)), inferior_limit, superior_limit)[0]


def b_k(function, x, k, half_period, inferior_limit, superior_limit):
    return (1/half_period) * scp.integrate.quad(function * np.sin(k * x * (np.pi / half_period)), inferior_limit, superior_limit)[0]


def main():
    inferior_limit, superior_limit = -np.pi, np.pi
    half_period = (superior_limit - inferior_limit) / 2
    x = np.linspace(inferior_limit, superior_limit, 1000)

    f = a_zero(desired_function, half_period, inferior_limit, superior_limit)
    total_k = 10
    for k in range(1, total_k+1):
        f += a_k(desired_function, x, k, half_period, inferior_limit, superior_limit)*np.cos(k*x*(np.pi/half_period)) +\
             b_k(desired_function, x, k, half_period, inferior_limit, superior_limit)*np.sin(k*x*(np.pi/half_period))

        plt.plot(x, f, label=f'k = {k}')

    plt.style.use('bmh')
    plt.plot(x, desired_function(x), colour='k')
    plt.legend()
    plt.show()


if __name__ == '__main__':
    main()
  1. 我遇到的第一个问题是在这些部分:
    scp.integrate.quad(function * np.cos(k * x * (np.pi / half_period)), inferior_limit, superior_limit)
    scp.integrate.quad(function * np.sin(k * x * (np.pi / half_period)), inferior_limit, superior_limit)
    。我收到一条错误消息,试图将一个函数与一个浮点数相乘,我想知道是否有其他方法可以将函数和余弦(或正弦)结合起来。
  2. 第二个问题是当我调用a_k或b_k时出现的警告
    Expected type '{__mul__}', got '(t: {__pow__}) -> Any' instead
    ,像这里:
    f += a_k(desired_function, x, k, half_period, inferior_limit, superior_limit)*np.cos(k*x*(np.pi/half_period))
    。我不明白为什么会出现这个警告,并且在调用 a_zero 时没有显示。

无论如何,我们将不胜感激。提前谢谢你!

python numpy math scipy signals
© www.soinside.com 2019 - 2024. All rights reserved.