首页 > 其他分享 >数学建模习题7.10

数学建模习题7.10

时间:2024-11-17 14:59:45浏览次数:1  
标签:plt 7.10 fit degree normal interp 建模 习题 data

`import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d, PchipInterpolator, CubicSpline
from scipy.optimize import curve_fit
from scipy.stats import norm

读取数据

file_path = '7.17.xISX' # 确保文件路径正确
data = pd.read_excel(file_path, header=None)
x_data = data.iloc[:, 0].values
y_data = data.iloc[:, 1].values

定义插值函数

x_interp = np.linspace(-2, 4.9, 400)
interp_functions = {
'Linear': interp1d(x_data, y_data, kind='linear', bounds_error=False, fill_value='extrapolate'),
'Cubic': interp1d(x_data, y_data, kind='cubic', bounds_error=False, fill_value='extrapolate'),
'PCHIP': PchipInterpolator(x_data, y_data, extrapolate=True),
'CubicSpline': CubicSpline(x_data, y_data, bc_type='natural', extrapolate=True)
}
y_interps = {name: func(x_interp) for name, func in interp_functions.items()}

绘制插值结果

plt.figure(figsize=(10, 6))
for name, y_interp in y_interps.items():
plt.plot(x_interp, y_interp, label=name)
plt.plot(x_data, y_data, 'o', label='Original Data')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Interpolation Methods Comparison')
plt.grid(True)
plt.show()

多项式拟合

degrees = range(1, 6)
coeffs = {}
residuals = {}
for degree in degrees:
coefficients, residual = np.polyfit(x_data, y_data, degree, cov=True)
residual_std = np.sqrt(residual[0, 0])
coeffs[degree] = coefficients
residuals[degree] = residual_std

for degree, coeffs_val in coeffs.items():
print(f"Degree {degree} Polynomial Coefficients: {coeffs_val}")
print(f"Residual Standard Deviation: {residuals[degree]:.4f}")

best_degree = min(residuals, key=residuals.get)
print(f"Best fitting polynomial degree: {best_degree}")
best_poly = np.poly1d(coeffs[best_degree])
y_poly_fit = best_poly(x_interp)

绘制多项式拟合结果

plt.figure(figsize=(10, 6))
plt.plot(x_interp, y_poly_fit, label=f"{best_degree}-degree Polynomial Fit")
plt.plot(x_data, y_data, 'o', label='Original Data')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Polynomial Fit')
plt.grid(True)
plt.show()

正态分布拟合

def normal_dist(x, mu, sigma):
return norm.pdf(x, mu, sigma)

params, params_covariance = curve_fit(normal_dist, x_data, y_data, p0=[np.mean(x_data), np.std(x_data)])
mu, sigma = params
x_normal_fit = np.linspace(min(x_data), max(x_data), 400)
y_normal_fit = normal_dist(x_normal_fit, mu, sigma)

绘制正态分布拟合结果

plt.figure(figsize=(10, 6))
plt.plot(x_normal_fit, y_normal_fit, label=f'Normal Distribution Fit\nmu={mu:.2f}, sigma={sigma:.2f}')
plt.plot(x_data, y_data, 'o', label='Original Data')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Normal Distribution Fit')
plt.grid(True)
plt.show()

print("学号后四位:3005")`


标签:plt,7.10,fit,degree,normal,interp,建模,习题,data
From: https://www.cnblogs.com/vvlin/p/18550550

相关文章

  • 习题7.10(2)
    1.代码实现点击查看代码importnumpyasnpimportpylabasplt#原始数据点x0=np.array([-2,-1.7,-1.4,-1.1,-0.8,-0.5,-0.2,0.1,0.4,0.7,1,1.3,1.6,1.9,2.2,2.5,2.8,3.1,3.4,3.7,4,4.3,4.6,4.9])y0=np.array([0.1029,0.1174,0.1316,0.144......
  • 数学建模习题8.4
    `importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.integrateimportsolve_ivp定义微分方程系统defsystem(t,state):x,y=statedxdt=-x-ydydt=x-y**3return[dxdt,dydt]定义时间跨度和初始条件t_span=(0,30)y0=[1,0.5]解微分方程so......
  • 数学建模习题7.7
    `importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.optimizeimportcurve_fit,leastsq,least_squares定义函数g(x,a,b)defg(x,a,b):return(10*a)/(10*b+(a-10*b)*np.exp(a*np.sin(x)))初始参数a=1.1b=0.01生成数据x_values......
  • 数学建模习题7.4
    `importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.interpolateimportgriddatadeff(x,y):x2=x2return(x2-2*x)*np.exp(-x2-y2-x*y)x_min,x_max=-3,3y_min,y_max=-4,4num_points=1000x_random=np.random.uniform(x_min,x_ma......
  • 数学建模习题7.3
    `importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.interpolateimportinterp1d,CubicSpline已知的温度和对应的体积T_known=np.array([700,720,740,760,780])V_known=np.array([0.0977,0.1218,0.1406,0.1551,0.1664])需要求解的温度T_query=......
  • 数学建模习题7.1
    `importnumpyasnpimportscipy.interpolateasspiimportscipy.integrateasspi_integrate定义函数g(x)defg(x):return((3x**2+4x+6)*np.sin(x))/(x**2+8*x+6)在区间[0,10]上等间距取1000个点x=np.linspace(0,10,1000)计算这些点处的函数值......
  • 2024年数维杯数学建模竞赛 问题D:城市韧性和可持续发展能力的评估 问题一 思路和代码
    所有数学建模竞赛思路和代码都会发布到专栏内,只需订阅一次,不需要每次都订阅,专栏内包含35个经典模型案例和历年优秀论文。不代写论文,内容可能达不到预期,请勿盲目订阅!!!更多详细思路请订阅专栏:https://blog.csdn.net/m0_52343631/category_12482955.htmlhttps://blog.csdn.net/m0......
  • 2024年数维杯数学建模竞赛 B题:空间变量的协同估计方法研究 问题二 详细思路和代码
    问题2:利用附件1中的数据研究目标变量与协同变量之间的相关性。选择两个协同变量作为目标变量的估计协同变量。目录步骤概述:具体步骤和代码实现:1.加载数据2.探索性数据分析(EDA)3.计算相关性4.选择协同变量5.建......
  • 第七章课后习题
    习题7.1点击查看代码importnumpyasnpfromscipy.interpolateimportinterp1dfromscipy.integrateimportquadimportmatplotlib.pyplotaspltg=lambdax:(3*x**2+4*x+6)*np.sin(x)/(x**2+8*x+6)x0=np.linspace(0,10,1000)y0=g(x0......
  • 第八章课后习题
    习题8.4点击查看代码fromscipy.integrateimportodeintimportnumpyasnpimportmatplotlib.pyplotasplt#设置Matplotlib不使用LaTeXplt.rc('font',size=15)plt.rc('text',usetex=False)#定义微分方程系统dz=lambdaz,t:[-z[0]**3-z[1],z[0]-......