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
the answer I found (with the help of ChatGPT and another question):