修正了矩阵运算

This commit is contained in:
_Karasu_ 2022-12-11 16:00:02 +08:00
parent e8404e1f9d
commit 278684310d
2 changed files with 6 additions and 15 deletions

View File

@ -57,18 +57,10 @@ def solve_equation(eq):
matrix = np.mat(matrix, int)
# 求解线性方程组
try:
result = np.linalg.solve(matrix, constant).tolist()
except np.linalg.LinAlgError:
# 将常数项取负,插入到矩阵的最后一列
constant = [-x for x in constant]
matrix = np.insert(matrix, matrix.shape[1], constant, axis=1)
# 再次尝试求解
try:
constant = np.zeros(matrix.shape[0], int)
result = sp.linalg.solve(matrix, constant).tolist()
except Exception as e:
print('无法配平' + str(e))
return None
result = sp.optimize.lsq_linear(matrix, constant, bounds=(0, None)).x.tolist()
except ValueError:
print('无法配平')
return None
# 将结果写入化学方程式,最后一个生成物的系数需要计算得到
last_substance = eq['right'][-1]
@ -76,7 +68,6 @@ def solve_equation(eq):
# 计算除最后一种生成物外的所有生成物包含last_atom的系数之和
sum_ = 0
index = 0
print(result)
for each in eq['left']:
for atom in each['atoms']:
if last_atom in atom:
@ -118,4 +109,4 @@ def expand_to_int(*args):
result = []
for each in fractions:
result.append(each.numerator * lcm // each.denominator)
return result
return result

View File

@ -9,7 +9,7 @@ import equation_solver
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
while True:
eq = input('请输入化学方程式:')
eq = input('请输入化学方程式:(输入exit退出)')
if eq == 'exit':
break
try: