python拟合三角函数
时间: 2023-10-01 16:10:11 浏览: 441
要在Python中拟合三角函数,可以使用scipy库中的optimize.curve_fit函数。首先,需要导入必要的库,如numpy和scipy.optimize。然后,可以使用以下代码来拟合sin函数:
```python
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as optimize
# 定义目标函数
def target_func(x, a, b, c):
return a * np.sin(b * x + c)
# 生成模拟数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x) + np.random.normal(0, 0.1, size=x.shape)
# 使用curve_fit进行拟合
p0 = [1, 1, 0 # 初始参数值
params, _ = optimize.curve_fit(target_func, x, y, p0=p0)
a, b, c = params
# 绘制原始数据和拟合曲线
plt.scatter(x, y, label='Original Data')
plt.plot(x, target_func(x, a, b, c), color='red', label='Fitted Curve')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
```
在上述代码中,我们定义了目标函数`target_func`来表示sin函数的形式。然后,我们生成了一组模拟数据,并使用`curve_fit`函数对这些数据进行拟合。通过指定初始参数值`p0`,函数将返回拟合后的参数值`params`。最后,我们使用`matplotlib`库将原始数据和拟合曲线绘制出来。这样就可以拟合三角函数了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [PyTorch中的三角函数:如何利用PyTorch实现三角函数操作?](https://blog.csdn.net/update7/article/details/129743241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [python数据分析之曲线拟合(2):三角函数sin/cos拟合](https://blog.csdn.net/kaever/article/details/109659367)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [【pytorch】拟合sin函数](https://blog.csdn.net/mimiduck/article/details/119852927)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文