I am coding a function that solves an arbitrary number of simultaneous equations. The number of equations is set by one of the parameters of the function and each equation is built from a number of symbols - as many symbols as there are equations. This means that I can't simply hardcode the equations, or even the symbols needed to put together the equations; the function needs to be able to handle any number of equations. So, my question is, how do I produce a list of symbols?
I have one possible solution, but my gut tells me that it's not going to be very efficient. Please let me know if there is a better way of doing this.
I'm new to SymPy and am still feeling my way about. As far as I can see, Symbols need to be defined with a string. Therefore, I can produce a series strings via appending an incrementing number to a letter (say 't0', 't1', etc), add them to a list and then create the symbols using those strings as parameters. Those symbols would themselves be stored in a list and would be used to produce the equations.
def solveEquations(numEquations): symbolNameList = [] symbolList = [] equationList = [] for i in range(numEquations): name = 't' + str(i) symbolNameList.append(name) symbolList.append(Symbol(name)) for i in range(numEquations): equation = 0 for sym in symbolList: equation += sym ** i # Or whatever structure the equation needs equationList.append(equation) #Then go on to solve the equations...
Is this the best way of doing this, or is there a more efficient approach?
Note that by default in SymPy the base of the natural logarithm is E (capital E ).
The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.
SymPy (as of now) is purely Python-based and hence slow.
The symbols
function can be used to easily generate lists of symbols
In [1]: symbols('a0:3') Out[1]: (a₀, a₁, a₂) In [2]: numEquations = 15 In [3]: symbols('a0:%d'%numEquations) Out[3]: (a₀, a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈, a₉, a₁₀, a₁₁, a₁₂, a₁₃, a₁₄)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With