python - 如何找到数值时间序列的多个最大值

标签 python max numerical-methods

我正在使用欧拉方法(在 Python 中)数值求解一阶微分方程。我从时间 t=0 开始构建解决方案,直到某个任意时间以大小为 0.05 的时间步长进行。结果解决方案的一个示例如下图所示 enter image description here

我想找到我们在该图中看到的最大值(以及它们出现的时间)并将它们存储在字典中。如果整个时间范围内只有一个最大值,我可以使用这段代码

y=[xinitial,viinitial,ainitial]            
t=0
maximum=-20000
maxai={}
h=0.05
ai=-2.1
for i in range(0,3701):
   dydt=computederivs(y)
   y = euler(y,dydt,h)
   t+=h
   if y[0]>maximum:
      maximum = y[0]
 maxai[ai]=maximum

因为我有多个局部最大值,所以我必须在时间 t 中移动时检测它们,方法是通过某种方式检查函数在爬升几个时间步后何时下降。我还需要将最大值存储在列表中,该列表是字典键的值。 我在想象这是一项足够普遍的任务,必须有众所周知的方法来或多或少地简单地完成它?

最佳答案

我建议使用 find_peaks来自 scipy.signal 模块。 此函数采用一维数组并通过简单比较相邻值来找到所有局部最大值。或者,可以通过指定峰属性的条件来选择这些峰的子集。

这是一个让您入门的代码片段:

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks

Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)
peaks = find_peaks(y)

plt.scatter(peaks[0], np.ones(f), c='red')
plt.plot(x, y)
plt.xlabel('sample(n)')
plt.ylabel('voltage(V)')
plt.show()

enter image description here

你的最大值:

print(peaks[0])
[ 400 2000 3600 5200 6800]

关于python - 如何找到数值时间序列的多个最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54270512/

相关文章:

math - 如何实现自适应步长 Runge-Kutta Cash-Karp?

php - Python Imports 不提供 PHP 中的输出

python - Django 异常和响应代码列表

python从嵌套字典中获取最小/最大值

mysql - sql - 为什么 SUM() 的 MAX() 不起作用?

c++ - 有效地从未排序的数组中获取前 50 个最高数字

python - 如何调试请求库?

python - 组合两个numpy数组以形成一个数组,每个数组中的最大值

f# - 柯里化(Currying)和多重积分

python - 使用 Screen 和 Bash 进行多处理