As part of a program, I am struggling to implement a function to solve a system of equations. First, I receive a set of equations from text input. Please note that the number of equations and thus variables are unknown, as well as the name of variables. For simplicity, I consider only two equations in a list of strings. Afterwards, equations are edited, variables are identified, and the guesses array is created.
from math import exp
import sympy
from sympy import sympify
eq_list = ["x + y**2 = 4", "exp(x) + x*y = 3"]
eq_list_altered = []
for eq in eq_list:
start, end = eq.split('=')
eq_list_altered.append(start + '-' + end)
guess = [0.1 for i in eq_list_altered]
vars_set = set()
for eq in eq_list_altered:
vars_set.update((sympify(eq)).free_symbols)
vars_lst = list(vars_set)
The second step is where I am struggling. The main issue is that the input can have n equations and n unknowns. WHilst the equations are easy to deal with, I am trying to find the simplest way to assign the variables to the guess values, i.e.:
def f(variables) :
x, y = variables # How to this for any variable name and len ?
res = []
for eq in eq_list_edit:
res.append(eval(eq))
return res
solution = opt.root(f, guess)
print(solution.x)
I already tried using locals(), globals() and dictionaries without success. It seems a simple procedure to set a list of variables equal to a list of values; however, after two days of searching and reading, I could not find a simple solution. The only one working is:
dict_tmp = {vars_lst[i]: variables[i] for i in range(len(vars_lst))}
print(dict_tmp)
for k in dict_tmp:
globals()['{}'.format(k)] = dict_tmp[k]
That may result in issues as the input is external. Thank you.