How to get integer answers while solving a chemical equation using Numpy

33 Views Asked by At

So I was asked to write a Python code to solve a chemical equation using echelon matrix for the Algebra course in Uni. everything is alright except that I want to have integer answers in the end and I don't know how to do so. In my solve_equation function, I am giving 1 to the free variable so that I can calculate other variables based on this. idk what other thing I can do since I am not very familiar with Python and I have just begun coding. this is my function so far (it is getting the reduced echelon matrix as input and return the coefficients):

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

I think I should change the input of the free variable based on its coefficients in the reduced echelon matrix

1

There are 1 best solutions below

0
hiiambobby On

the answer I found (with the help of ChatGPT and another question):

def solve_equation(matrix):

    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