SymPy:自动构建方程

SymPy: automatic construction of equations

我在别处发现 x = sp.symbols('x1:{}'.format(n)) 创建 n 个变量的集合,绑定到变量 x。 现在,我想使用 https://docs.sympy.org/latest/modules/solvers/solveset.html#sympy.solvers.solveset.nonlinsolve 求解非线性方程组。我可以构造一个包含的字符串 我的方程组中每一行的表达式, 例如像 x1**2+4*x2**3 之类的东西。 如何让 sympy 将这些转换成自己的方程式? 在文档中给出的例子中,我们写 类似于 [x1**2+4*x2**3,2*x1+3*x3] 并将其传递给 solve(), 但是如何构造这些表达式(它们的类型是什么?) 自动进行,而不是对它们进行硬编码?

上面的表达式是符号乘积的总和,在Add

的sympy实例中

来自documentation

All symbolic things are implemented using subclasses of the Basic class. First, you need to create symbols using Symbol("x") or numbers using Integer(5) or Float(34.3). Then you construct the expression using any class from SymPy. For example Add(Symbol("a"), Symbol("b")) gives an instance of the Add class. You can call all methods, which the particular class supports.

在您的示例中,您需要将 x1x2x3 声明为符号:

x1, x2, x3 = symbols('x1 x2 x3')

定义符号后,sympy 会自动将字符串转换为自己的表达式以进行计算。要检查 sympy 表达式的类型,请使用 sympify

a = Symbol("a")
b = Symbol("b")
c = 'a**2 + b'
print c
(a + b)**2
type(c)
# string

from sympy import sympify
sympify(c)
type(sympify(c))
# <′...′>