7.3
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from scipy.interpolate import CubicSpline, interp1d
import scipy.integrate as si
t = np.arange(700, 800, 20)
v = np.array([0.0977, 0.1218, 0.1406, 0.1551, 0.1664])
f = interp1d(t, v, kind="linear")
v1 = f([750, 770])
print('线性插值:', v1)
cs = CubicSpline(t, v)
v2 = cs([750, 770])
print('三次样条插值:', v2)
plt.figure(dpi=600, figsize=(7, 4))
plt.plot(t, v, '*-')
plt.plot(t, cs(t))
plt.legend(['线性插值', '三次样条插值'])
结果
7.4
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
from numpy.random import uniform
def f(x, y):
return (x ** 2 - 2 * x) * np.exp(x ** 2 * y ** 2 - 9)
num_points = 100
x_random = uniform(-3, 3, num_points)
y_random = uniform(-4, 4, num_points)
z_random = f(x_random, y_random)
grid_x, grid_y = np.mgrid[-3:3:100j, -4:4:100j]
grid_z = griddata((x_random, y_random), z_random, (grid_x, grid_y), method='cubic')
plt.contourf(grid_x, grid_y, grid_z, levels=20)
plt.colorbar()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interpolation Result of f(x,y)')
plt.show()
结果
7.7
(1)import numpy as np
from scipy.optimize import curve_fit
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_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)
popt, pcov = curve_fit(g, x_observed, y_observed)
print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果
(2)import numpy as np
from scipy.optimize import leastsq
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_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)
def error_function(params, x, y):
a_fit, b_fit = params
y_fit = g(x, a_fit, b_fit)
return y - y_fit
initial_guess = (1.0, 0.01)
popt, pcov = leastsq(error_function, initial_guess, args=(x_observed, y_observed))
print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果
(3)import numpy as np
from scipy.optimize import least_squares
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_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)
def error_function(params, x, y):
a_fit, b_fit = params
y_fit = g(x, a_fit, b_fit)
return y - y_fit
initial_guess = (1.0, 0.01)
result= least_squares(error_function, initial_guess, args=(x_observed, y_observed))
popt = result.x
print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果
7.10
(1)
import numpy as np
from scipy.interpolate import lagrange, interp1d, CubicSpline
import matplotlib.pyplot as plt
x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]
x = np.linspace(-2, 4.9, 100)[:, np.newaxis]
y1 = lagrange(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
y2 = interp1d(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
y3 = CubicSpline(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
plt.subplot(131)
plt.plot(x, y1)
plt.title('拉格朗日插值')
plt.scatter(x0, y0, c='r', marker='o', label='原始数据点')
plt.xlabel('自变量')
plt.ylabel('因变量')
plt.legend(['拉格朗日插值', '原始数据点'])
plt.subplot(132)
plt.plot(x, y2)
plt.title('分段线性插值')
plt.scatter(x0, y0, c='r', marker='o')
plt.xlabel('自变量')
plt.ylabel('因变量')
plt.legend(['分段线性插值', '原始数据点'])
plt.subplot(133)
plt.plot(x, y3)
plt.title('三次样条插值')
plt.scatter(x0, y0, c='r', marker='o')
plt.xlabel('自变量')
plt.ylabel('因变量')
plt.legend(['三次样条插值', '原始数据点'])
plt.show()
结果
7.10
(2)import numpy as np
from scipy.optimize import curve_fit
x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]
x = np.linspace(-2, 4.9, 100)[:, np.newaxis]
def polynomial_fit(x, y, degree):
def polynomial_function(x, *params):
return np.polyval(params, x)
popt, pcov = curve_fit(polynomial_function, x.flatten(), y.flatten(), p0=np.ones(degree + 1))
fx = lambda x: polynomial_function(x, *popt)
mse = np.mean((y.flatten() - fx(x.flatten())) ** 2)
rmse = np.sqrt(mse)
return fx, popt, rmse
best_rmse = float('inf')
best_degree = None
best_fit_params = None
for degree in range(1, 10):
fx, fit_params, rmse = polynomial_fit(x0, y0, degree)
if rmse < best_rmse:
best_rmse = rmse
best_degree = degree
best_fit_params = fit_params
print(f"选择的多项式阶次: {best_degree}")
print(f"多项式系数: {best_fit_params}")
print(f"剩余标准差(RMSE): {best_rmse}")
结果
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]
x = np.linspace(-2, 4.9, 100)[:, np.newaxis]
def normal_distribution(x, mu, s):
return 1 / (np.sqrt(2 * np.pi) * s) * np.exp(-(x - mu) ** 2 / (2 * s ** 2))
popt, pcov = curve_fit(normal_distribution, x0.flatten(), y0.flatten(), p0=np.random.rand(1, 2))
f = lambda x: normal_distribution(x, popt[0], popt[1])
plt.subplot(111)
plt.plot(x, f(x))
plt.title('拟合的正态分布密度函数')
plt.show()
结果