首页 > 其他分享 >2.13 已知f(x)=(|x+1|-|x-1|)/2+sinx,g(x)=(|x+3|-|x-3|)/2+cosx,求下列超定方程组的最小二乘解

2.13 已知f(x)=(|x+1|-|x-1|)/2+sinx,g(x)=(|x+3|-|x-3|)/2+cosx,求下列超定方程组的最小二乘解

时间:2024-09-12 20:02:21浏览次数:13  
标签:guess sinx x2 print np 二乘解 超定 y1 y2

点击查看代码
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("学号:2023310143004")

标签:guess,sinx,x2,print,np,二乘解,超定,y1,y2
From: https://www.cnblogs.com/howoo0808/p/18410944

相关文章