首页 > 其他分享 >7.1 7.3 7.4 7.7 7.10

7.1 7.3 7.4 7.7 7.10

时间:2024-11-17 23:33:23浏览次数:1  
标签:plt 7.10 fit interp 7.3 7.1 values np data

7.1

点击查看代码
import numpy as np
import scipy.interpolate as spi
import scipy.integrate as spi_integrate

def g(x):
    return ((3*x**2 + 4*x + 6) * np.sin(x)) / (x**2 + 8*x + 6)

x_values = np.linspace(0, 10, 1000)

y_values = g(x_values)

spline = spi.CubicSpline(x_values, y_values)

def h(x):
    return spline(x)

integral_g, _ = spi_integrate.quad(g, 0, 10)

x_fine = np.linspace(0, 10, 10000)
y_fine = h(x_fine)
integral_h = np.trapz(y_fine, x_fine)

print(f"积分 g(x) 从 0 到 10 的结果: {integral_g}")
print(f"积分 h(x) 从 0 到 10 的结果: {integral_h}")
print("3010")

7.3

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d, CubicSpline

T = np.array([700, 720, 740, 760, 780])
V = np.array([0.0977, 0.1218, 0.1406, 0.1551, 0.1664])

T_interp = np.array([750, 770])

f_linear = interp1d(T, V, kind='linear')
V_linear_interp = f_linear(T_interp)

cs = CubicSpline(T, V)
V_cubic_interp = cs(T_interp)

x = np.linspace(700, 780, 400)
print(f"线性插值结果: T={T_interp} 对应的 V={V_linear_interp}")
print(f"三次样条插值结果: T={T_interp} 对应的 V={V_cubic_interp}")
print("3010")
plt.figure(figsize=(10, 6))
plt.plot(T, V, 'o', label='原始数据点')
plt.plot(x, f_linear(x), '-', label='线性插值')
plt.plot(x, cs(x), '--', label='三次样条插值')
plt.scatter(T_interp, V_linear_interp, color='red', label='线性插值点')
plt.scatter(T_interp, V_cubic_interp, color='green', label='三次样条插值点')
plt.xlabel('温度 T')
plt.ylabel('体积 V')
plt.title('过热蒸汽体积随温度变化的插值')
plt.legend()
plt.grid(True)
plt.show()

7.4

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

def f(x, y):
    return (x*2 - 2*x) * np.exp(-x*2 - y**2 - x*y)

x_min, x_max = -3, 3
y_min, y_max = -4, 4

num_points = 1000
x_random = np.random.uniform(x_min, x_max, num_points)
y_random = np.random.uniform(y_min, y_max, num_points)

z_random = f(x_random, y_random)

grid_x, grid_y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j]

grid_z = griddata((x_random, y_random), z_random, (grid_x, grid_y), method='cubic')

plt.figure(figsize=(10, 8))
plt.contourf(grid_x, grid_y, grid_z, levels=50, cmap='viridis') # 使用等高线图填充
plt.colorbar(label='f(x, y)')
plt.scatter(x_random, y_random, c='red', s=10, label='随机散乱点') # 绘制随机散乱点
plt.title('函数f(x, y)的插值结果')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print("3010")

7.7

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, leastsq, least_squares
from scipy.constants import e

def g(x, a, b):
    return (10 * a) / (10 * b + (a - 10 * b) * np.exp(a * np.sin(x)))

a = 1.1
b = 0.01

x_values = np.arange(1, 21)

y_values = g(x_values, a, b)

for i, (xi, yi) in enumerate(zip(x_values, y_values), start=1):
    print(f"({xi}, {yi:.6f})")

popt_curve_fit, pcov_curve_fit = curve_fit(g, x_values, y_values, p0=[a, b])
y_fit_curve_fit = g(x_values, *popt_curve_fit)

def func_leastsq(params, x, y):
    return y - g(x, *params)

popt_leastsq = leastsq(func_leastsq, [a, b], args=(x_values, y_values))[0]
y_fit_leastsq = g(x_values, *popt_leastsq)

popt_least_squares = least_squares(func_leastsq, [a, b], args=(x_values, y_values)).x
y_fit_least_squares = g(x_values, *popt_least_squares)

print("\ncurve_fit parameters:", popt_curve_fit)
print("leastsq parameters:", popt_leastsq)
print("least_squares parameters:", popt_least_squares)

plt.figure(figsize=(10, 6))
plt.scatter(x_values, y_values, label='Simulated data', color='red')
plt.plot(x_values, y_fit_curve_fit, label='curve_fit', linestyle='-')
plt.plot(x_values, y_fit_leastsq, label='leastsq', linestyle='--')
plt.plot(x_values, y_fit_least_squares, label='least_squares', linestyle='')
plt.xlabel('x')
plt.ylabel('g(x)')
plt.legend()
plt.title('Fitting of g(x) using curve_fit, leastsq, and least_squares')
plt.grid(True)
plt.show()
print("3010")

7.10

点击查看代码
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.xlsx'
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("3010")

标签:plt,7.10,fit,interp,7.3,7.1,values,np,data
From: https://www.cnblogs.com/zhhhhha/p/18551384

相关文章

  • 习题7.3
    1.代码实现点击查看代码importnumpyasnpfromscipy.interpolateimportinterp1d,CubicSplineimportmatplotlib.pyplotasplt#给定数据T=np.array([700,720,740,760,780])V=np.array([0.0997,0.1218,0.1406,0.1551,0.1664])#要插值的温度点T_interp......
  • 习题7.10(3)
    1.代码实现点击查看代码importnumpyasnpimportpylabaspltfromscipy.optimizeimportcurve_fit#原始数据点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.......
  • 数学建模习题7.10
    `importnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltfromscipy.interpolateimportinterp1d,PchipInterpolator,CubicSplinefromscipy.optimizeimportcurve_fitfromscipy.statsimportnorm读取数据file_path='7.17.xISX'#确保文件......
  • 习题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......
  • 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)gh=interp1d(x0,......
  • 数学建模习题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)计算这些点处的函数值......
  • 【FMC128D】基于VITA57.1标准的8通道250MSPS采样率16位AD采集FMC子卡(直流耦合)
    ​ 产品概述FMC128D是一款8通道250MHz采样率16位分辨率直流耦合AD采集FMC子卡,符合VITA57.1规范,可以作为一个理想的IO模块耦合至FPGA前端,8通道AD将模拟信号数字化后通过高带宽的FMC连接器(HPC)连接至FPGA,从而大大降低了系统信号延迟。该板卡支持板上可编程采样时钟和外部参考时钟......
  • 习题7.10(1)
    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.1448......
  • 【FMC155A】基于VITA57.1标准的2路500MSPS/1GSPS/1.25GSPS 14位AD采集FMC子卡模块(交流
    ​板卡概述FMC155A是一款基于VITA57.1标准的,实现2路14-bit、500MSPS/1GSPS/1.25GSPS采样率交流耦合ADC同步采集FMC子卡模块。该模块遵循VITA57.1规范,可直接与FPGA载卡配合使用,板卡ADC器件采用ADI的AD9680芯片,该芯片具有两个模拟输入通道和两个JESD204B输出数据通道对,可用于高达2......