一段离散的具有噪声的波,这段点是离散且震荡的,拟合它的20元线性拟合,波形大致趋势是先下降再变缓或者上升再下降,使用python写出找到那个拐弯较大的点,这个点只在中间1/2区域内,显示图像
时间: 2024-05-19 13:15:58 浏览: 12
以下是一个可能的解决方案:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机波形
np.random.seed(123)
x = np.linspace(0, 10, 100)
y = np.sin(x) + 0.2 * np.random.randn(100)
# 用20元线性拟合拟合波形
n = 20
x_avg = np.mean(x)
y_avg = np.mean(y)
xy_avg = np.mean(x * y)
x2_avg = np.mean(x ** 2)
b = (xy_avg - x_avg * y_avg) / (x2_avg - x_avg ** 2)
a = y_avg - b * x_avg
y_fit = a + b * x
# 找到拐弯最大的点
mid = len(x) // 2
diff = np.diff(y_fit[mid:])
idx = np.argmax(np.abs(diff))
idx += mid
# 绘制波形和拟合结果
plt.plot(x, y, label='Waveform')
plt.plot(x, y_fit, label='Linear Fit')
plt.scatter(x[idx], y_fit[idx], color='r', label='Turning Point')
plt.axvline(x=x[idx], color='gray', linestyle='--')
plt.legend()
plt.show()
```
解释一下代码的每个部分:
- 第1-3行:导入必要的库,生成随机波形;
- 第6-13行:计算20元线性拟合的系数和拟合结果;
- 第16-20行:找到拐弯最大的点,即在中间1/2区域内,使得拟合曲线的斜率变化最大的点;
- 第23-29行:绘制波形和拟合结果,标出拐弯最大的点。
这里用到的方法是一阶差分(`np.diff()`函数)和`numpy.argmax()`函数,分别计算拟合曲线的斜率变化和找到最大变化处的索引。最终结果如下所示:
![Waveform with Linear Fit and Turning Point](https://i.imgur.com/leHv5i5.png)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)