You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用np.trapz计算温度数据集一阶傅里叶系数及积分限设置问题

问题描述

我有一组本质为正弦特性的数据集,大致格式如下:

TW-240-run1.txt

Point Number     Temperature 
0    51.504781 
 1   51.487722 
 2   51.487722 
 3   51.828893 
 4   51.828893 
 5   51.436547 
 6   51.368312 
 7   51.726542 
 8   51.368312 
 9   51.317137 
 10      51.317137 
 11      51.283020 
 12      51.590073 
.
.
.
9599     51.675366

导入数据的绘制图
我的任务是使用数值积分方法求解该数据集的基波/一阶傅里叶系数a_n和b_n,本次我使用numpy库的np.trapz实现梯形法则进行计算,傅里叶系数a_n、b_n的计算公式如下:
傅里叶系数计算公式
其中τ为正弦函数的周期,我的场景下τ=240秒(对应数据表的第240个点),因此积分上下限为0到240,公式中的T(t)为本次数据集,n取值为1。
我当前尝试计算傅里叶系数的代码如下:

# Packages
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
 
#input data from datasheet, the loadtxt below takes in the data from t = 0s to t = 240s
x1, y1 = np.loadtxt(r'C:\Users\Sidharth\Documents\y2python\y2python\thermal_4min_a.txt', unpack=True, skiprows=3)



tau_4min = 240.0


def cosine(period, t, n):
    return np.cos((2*np.pi*n*t)/(period)) #defines the cos term for the a_n formula

def sine(period, t, n): #defines the sin term for the a_n formula
    return np.sin((2*np.pi*n*t)/(period))

a_1_4min = (2/tau_4min)*np.trapz((y1*cos_term_4min), x1) #implement a_n formula (trapezium rule for T(t)*cos)
print('a_1 is', a_1_4min)

b_1_4min = (2/tau_4min)*np.trapz((y1*sin_term_4min), x1) #implement b_n formula (trapezium rule for T(t)*cos)
print('b_1 is', b_1_4min)

这段代码目前仅读取了0~240秒对应的数据点,将其与公式中的正弦/余弦项相乘后调用np.trapz计算,但我发现得到的傅里叶系数结果不正确。
我的问题如下:
如果我导入完整数据集,给np.trapz设置0到240的积分限,而非仅导入0~240区间的数据点再做乘积后调用np.trapz(0和240为指定积分上下限),这样修改后代码是否可以得到正确结果?

解答

该修改方式无法直接得到正确结果,你当前代码的问题和正确实现方案如下:

  1. 现有代码存在基础语法错误
    你已经定义了cosine和sine两个函数,但实际计算时用到的cos_term_4min和sin_term_4min没有被定义赋值,程序根本无法正常运行,首先要补充这两个项的计算逻辑。
  2. np.trapz没有直接指定积分上下限的参数
    np.trapz的计算逻辑是对输入的整段y和对应x序列做梯形积分,没有单独设置积分区间的参数。如果导入全量数据集,需要先将x、y序列中处于[0,240]区间的部分切片筛选出来,再传给np.trapz计算,直接传入全量数据只会得到整个数据长度的积分结果,必然错误。
  3. 要确认时间序列的单位匹配
    你提到第240个点对应240秒,需要确认你读取的x1列是实际的秒级时间,还是只是点序号。如果是点序号,需要手动构造时间序列,保证和周期τ的单位一致。

下面是修正后的可运行代码示例:

# 导入依赖包
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

# 导入完整数据集
x_all, y_all = np.loadtxt(r'C:\Users\Sidharth\Documents\y2python\y2python\thermal_4min_a.txt', unpack=True, skiprows=3)

tau_4min = 240.0
# 筛选0~240秒区间的数据,若x_all是点序号,将条件改为x_all < 240即可
mask = (x_all >= 0) & (x_all <= tau_4min)
x1 = x_all[mask]
y1 = y_all[mask]

def cosine(period, t, n):
    return np.cos((2*np.pi*n*t)/(period))

def sine(period, t, n):
    return np.sin((2*np.pi*n*t)/(period))

# 计算正余弦项
cos_term_4min = cosine(tau_4min, x1, n=1)
sin_term_4min = sine(tau_4min, x1, n=1)

# 计算一阶傅里叶系数
a_1_4min = (2/tau_4min)*np.trapz(y1 * cos_term_4min, x1)
print('a_1是', a_1_4min)

b_1_4min = (2/tau_4min)*np.trapz(y1 * sin_term_4min, x1)
print('b_1是', b_1_4min)

内容的提问来源于stack exchange,提问作者sid2001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:45:00