import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math
def plot_data(x, y):
# 绘制原始数据的散点图
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
def fit_func(x, a, b, c, d, e):
# return a*x +b
return a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e
def fit_data(x, y):
# 使用Levenberg-Marquardt算法拟合
popt, _ = curve_fit(fit_func, x, y)
a, b, c, d, e = popt
print(a,b,c,d,e)
y_pred = fit_func(x, a, b, c, d, e)
integral = np.trapz(y_pred, x) # 计算预测曲线下的积分值
return y_pred, integral
# 读取CSV文件
data = pd.read_csv('data.csv')
result = []
data_len = data.shape[0]
for i in range(data_len):
row = data.iloc[i]
#print(row)
j = 40
columns = [f'Amp_{0.5 * n + 1}' for n in range(0, j)]
x = range(j)
x = np.array(x)
y = row[columns]
y_pred, integral = fit_data(x, y)
print(y_pred)
print(max(y_pred),max(x))
integral = max(y_pred)*max(x) - integral
result.append(integral)
# print(y_pred)
# print("Integral:", integral)
# y_pred=pd.Dataframe(data = y_pred)
print(result)
# 创建包含结果的数据框
result_df = pd.DataFrame({'Integral': result})
# 保存为CSV文件
result_df.to_csv('result.csv', index=False)
拟合抛物线,并求线上的面积-python
最新推荐文章于 2024-08-15 22:18:26 发布