2.7

2023310143015發表於2024-10-28


程式碼

點選檢視程式碼
import numpy as np
import pandas as pd
import sympy as sp
sp.init_printing(use_unicode=True)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='cm'
# Times New Roman + SimSun + WFM Sans SC
# simsum宋體, times new roman -*, simhei黑體, kaiti楷體,
# dengxian等線, fangsong仿宋, Microsoft Yahei微軟雅黑
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
# plt.rcParams['figure.figsize'] = [4, 3]
# plt.rcParams['font.size'] = 12
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
from scipy.optimize import root
fx = lambda x: [
    4*x[0] + 2*x[1] - x[2] - 2,
    3*x[0] - x[1] + 2*x[2] - 10,
    11*x[0] + 3*x[1] - 8
]
root(fx, [0, 0, 0])
A = np.array([[4, 2, -1], [3, -1, 2], [11, 3, 0]])
b = np.array([[2], [10], [8]])
Ab = np.hstack([A, b])
r1 = np.linalg.matrix_rank(A)
r2 = np.linalg.matrix_rank(Ab)
print(f'{r1 = }, {r2 = }')
x = np.linalg.pinv(A)@b
np.round(x, 4)
from scipy.optimize import least_squares
f = lambda x: [
    2*x[0] + 3*x[1] + 1*x[2],
    1*x[0] - 2*x[1] + 4*x[2],
    3*x[0] + 8*x[1] - 2*x[2],
    4*x[0] - 1*x[1] + 9*x[2]
]
least_squares(f, [1, 2, 3])

相關文章