点击查看代码
import numpy as np
def f(x):
return (abs(x + 1) - abs(x - 1)) / 2 + np.sin(x)
def g(x):
return (abs(x + 3) - abs(x - 3)) / 2 + np.cos(x)
# 假设我们有一些初始猜测值(这里只是随机选择的)
x1_guess = 0.5
x2_guess = 1.0
y1_guess = 0.2
y2_guess = 0.3
# 定义方程组矩阵A和向量b
def create_system(x1, x2, y1, y2):
A = np.array([
[0, 0, 3*f(y1), 4*g(y2)],
[2, 0, 2*f(y1), 6*g(y2)],
[f(x1), 3*g(x2), -1, 0],
[4*f(x1), g(x2), 0, -1],
[1, -3, 0, -10*f(y1)],
])
b = np.array([-1, -2, -3, -1, 2])
return A, b
# 使用初始猜测值来创建方程组
A, b = create_system(x1_guess, x2_guess, y1_guess, y2_guess)
# 使用numpy.linalg.lstsq求解最小二乘解
sol, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
print("最小二乘解:")
print("x1 =", sol[0])
print("x2 =", sol[1])
print("y1 =", sol[2])
print("y2 =", sol[3])
print("残差平方和:", residuals[0])
print("学号:3004")
![](https://img2024.cnblogs.com/blog/3513959/202410/3513959-20241014223019534-1601858620.png)