Reputation: 406
I would like to add a functionality to solve systems of linear equations to my python based editor. I am looking for a module that would be able to parse a string such as the one below:
sample_volume=20
final_concentration=0.55
ethanol_concentration=0.96
final_volume = ethanol_vol+sample_volume
final_concentration*final_volume=ethanol_vol*ethanol_concentration
And solve for the values of all variables.
I have implemented a quick and dirty script using sympy that does this, see here for a Jupyter notebook.
I think that this must have been implemented by someone in a more robust way, I would like to avoid reinventing the wheel here.
Does anyone know of any alternative implementation that are more robust (have tests etc)?
Additionally, according to the sympy docs, sympy.solveset
should be used instead of sympy.solve
.
I cannot make this work with a list of equations as in my example. Can someone proficient in sympy guide me how to use solveset with an equation system such as this.
Upvotes: 1
Views: 311
Reputation: 304
In [2]: sample_volume=20
...: final_concentration=0.55
...: ethanol_concentration=0.96
...:
In [4]: fv,ev = symbols('fv,ev')
In [5]: expr1 = fv - ev+sample_volume
In [6]: expr2 = final_concentration*fv - ev*ethanol_concentration
In [7]: solve([expr1,expr2], [fv,ev])
Out[7]: {ev: -26.8292682926829, fv: -46.8292682926829}
# I will recommend to use solveset's linear system solver (linsolve)
In [8]: linsolve([expr1,expr2], [fv,ev])
Out[8]: {(-46.8292682926829, -26.8292682926829)}
Upvotes: 2