如何使用 Numpy 求解化学方程时获得整数答案

问题描述 投票:0回答:1

所以我被要求为大学的代数课程编写一个Python代码来使用梯形矩阵求解化学方程。一切都很好,除了我想最后得到整数答案,但我不知道该怎么做。在我的solve_equation函数中,我将1赋予自由变量,以便我可以基于此计算其他变量。不知道我还能做什么,因为我对 Python 不太熟悉并且刚刚开始编码。到目前为止,这是我的函数(它获取简化的梯形矩阵作为输入并返回系数):

def solve_equation(matrix):
    m, n = matrix.shape
    solution = {}
    
    # Iterate over each row to find the pivot variable and calculate its value
    for i in range(m):
        pivot_column = np.argmax(matrix[i, :-1])
        if matrix[i, pivot_column] == 0:
            continue  # Skip trivial equations
        variable_index = pivot_column
        variable_value = matrix[i, -1] / matrix[i, pivot_column]
        if(variable_value < 0):
            variable_value *= -1
        solution[f'X{variable_index + 1}'] = variable_value

    # Handle free variables
    for j in range(n - 1):
        if f'X{j + 1}' not in solution:
            # Assign a value of 1 to free variables
            solution[f'X{j + 1}'] = 1
            free_var_index = j
            # Iterate through the matrix to adjust values of basic variables
            for i in range(m):
                if i != free_var_index:
                    coefficient = matrix[i, free_var_index]
                    if coefficient < 0 :
                        coefficient *= -1
                    solution[f'X{i + 1}'] += coefficient * solution[f'X{j + 1}']

    return solution

我认为我应该根据简化梯队矩阵中的系数来更改自由变量的输入

python numpy matrix linear-algebra
1个回答
0
投票

我找到的答案(在 ChatGPT 和另一个问题的帮助下):

def 求解方程(矩阵):

m, n = matrix.shape
solution = {}
coeffs = {}

# Iterate over each row to find the pivot variable and calculate its value
for i in range(m):
    pivot_column = np.argmax(matrix[i, :-1])
    if matrix[i, pivot_column] == 0:
        continue  # Skip trivial equations
    variable_index = pivot_column
    variable_value = matrix[i, -1] / matrix[i, pivot_column]
    solution[f'X{variable_index + 1}'] = variable_value

# finding the free variables
for j in range(n - 1):
    if f'X{j + 1}' not in solution:
        # here I am assiging 1 to the free variable so that I can calculate others based on it
        solution[f'X{j + 1}'] = 1
        free_var_index = j
        # Iterate through the matrix to adjust values of basic variables
        for i in range(m):
            if i != free_var_index:
                coefficient = matrix[i, free_var_index]
                solution[f'X{i + 1}'] += coefficient * solution[f'X{j + 1}']

# I wanted to have integer answers in the end so here we convert numbers to integer by claculating the LCM
for var, value in solution.items():
    if var.startswith('X'):
        coeffs[var] = value

fractions = [Fraction(val).limit_denominator(MAX_DENOM) for val in coeffs.values()]
ratios = np.array([(f.numerator, f.denominator) for f in fractions])
factor = np.lcm.reduce(ratios[:,1])


for var, value in solution.items():
    if var.startswith('X'):
        solution[var] *= factor

return solution
© www.soinside.com 2019 - 2024. All rights reserved.