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:
我想添加一个功能来解决线性方程组到我的基于python的编辑器。我正在寻找一个能够解析字符串的模块,如下所示:
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.
我已经使用sympy实现了一个快速而肮脏的脚本,请参阅此处查看Jupyter笔记本。
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.
另外,根据sympy docs,应该使用sympy.solveset而不是sympy.solve。我不能用我的例子中的方程列表来完成这项工作。精通同情的人可以指导我如何使用像这样的方程系统来解决问题。
1 个解决方案
#1
2
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)}
#1
2
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)}