如何用Python构造函数实现线性方程组求解类?
线性方程组类实现修正方案
原代码核心问题
- 构造函数参数未实际利用,硬编码了三元方程组的系数与常数项,完全丧失复用性
solve方法逻辑残缺,既无返回结果也未处理求解异常- 未实现解的验证功能,也未按需求区分二元、三元方程组的子类
完整实现代码
import numpy as np class LinearSystem: """线性方程组父类,提供通用求解与解验证功能""" def __init__(self, coeff_matrix, const_terms): self.coeff_matrix = np.array(coeff_matrix, dtype=np.float64) self.const_terms = np.array(const_terms, dtype=np.float64) self.solution = None # 存储方程组的解 def solve(self): """求解线性方程组,处理奇异矩阵(无解/无穷多解)的异常情况""" try: self.solution = np.linalg.solve(self.coeff_matrix, self.const_terms) return self.solution except np.linalg.LinAlgError: # 矩阵奇异时返回最小二乘近似解 self.solution, _, _, _ = np.linalg.lstsq(self.coeff_matrix, self.const_terms, rcond=None) print("方程组无解或有无穷多解,返回最小二乘近似解") return self.solution def is_solution(self, test_values): """验证一组数值是否为当前方程组的解(考虑浮点精度误差)""" test_values = np.array(test_values, dtype=np.float64) error = np.dot(self.coeff_matrix, test_values) - self.const_terms return np.allclose(error, np.zeros_like(error), atol=1e-6) class BinaryLinearSystem(LinearSystem): """二元线性方程组子类,限定输入维度为2x2系数矩阵+2维常数项""" def __init__(self, coeff_matrix, const_terms): if np.shape(coeff_matrix) != (2, 2) or len(const_terms) != 2: raise ValueError("二元方程组必须传入2x2系数矩阵和2个常数项") super().__init__(coeff_matrix, const_terms) class TernaryLinearSystem(LinearSystem): """三元线性方程组子类,限定输入维度为3x3系数矩阵+3维常数项""" def __init__(self, coeff_matrix, const_terms): if np.shape(coeff_matrix) != (3, 3) or len(const_terms) != 3: raise ValueError("三元方程组必须传入3x3系数矩阵和3个常数项") super().__init__(coeff_matrix, const_terms) def generate_random_binary_system(): """随机生成有唯一解的二元线性方程组(确保系数矩阵可逆)""" while True: coeff = np.random.randint(-10, 11, size=(2, 2)) if np.linalg.det(coeff) != 0: break const_terms = np.random.randint(-20, 21, size=2) return BinaryLinearSystem(coeff, const_terms) def generate_random_ternary_system(): """随机生成有唯一解的三元线性方程组(确保系数矩阵可逆)""" while True: coeff = np.random.randint(-10, 11, size=(3, 3)) if np.linalg.det(coeff) != 0: break const_terms = np.random.randint(-20, 21, size=3) return TernaryLinearSystem(coeff, const_terms) # 测试代码 if __name__ == "__main__": # 测试原问题中的三元方程组 ternary_coeff = [[8, 3, -2], [-4, 7, 5], [3, 4, -12]] ternary_const = [9, 15, 35] ts = TernaryLinearSystem(ternary_coeff, ternary_const) sol = ts.solve() print("三元方程组的解:", sol) print("解验证结果:", ts.is_solution(sol)) # 随机二元方程组测试 print("\n--- 随机二元方程组测试 ---") bs = generate_random_binary_system() sol_bs = bs.solve() print("系数矩阵:\n", bs.coeff_matrix) print("常数项:", bs.const_terms) print("解:", sol_bs) print("解验证结果:", bs.is_solution(sol_bs)) # 随机三元方程组测试 print("\n--- 随机三元方程组测试 ---") ts_rand = generate_random_ternary_system() sol_ts_rand = ts_rand.solve() print("系数矩阵:\n", ts_rand.coeff_matrix) print("常数项:", ts_rand.const_terms) print("解:", sol_ts_rand) print("解验证结果:", ts_rand.is_solution(sol_ts_rand))
实现说明
- 父类
LinearSystem:封装通用逻辑,包括输入初始化、核心求解(含异常处理)、解验证(用np.allclose规避浮点精度问题) - 子类限定:通过构造函数维度校验,强制二元/三元方程组的输入规范,避免非法数据传入
- 随机生成逻辑:循环生成可逆矩阵(行列式非0),确保生成的方程组有唯一解
- 解验证:通过计算
Ax - b的误差值,判断测试数值是否符合方程组要求
内容的提问来源于stack exchange,提问作者Полишук Макс
相关产品推荐
相关产品推荐

