有没有办法将等式符号化地传递给 sympy 函数?

Is there a way to pass an equation symbolically into a function for sympy?

由此

import sympy as sp

x,y,z = sp.symbols("x y z")
sp.Ep(x,y/z)

对此

#varibles = array
#equation = ????
def solver(variables,equation):
    #Looping through variables array and converting variables to sympy objects 
    for var in variables:
        var = sp.symbols(var)
    
    #Generate sympy Equation
    equation = sp.Ep(equation)

variables = [x,y,z]
equation = x,y/z #invalid code

solver(variables,equation)

我正在创建一个函数,它能够接受一个包含 x 个变量和 x-1 个值的方程,然后以符号方式求解缺失的变量,然后 return 使用这些值的数值答案提供。

我只包含了一小部分代码,在这些代码中我无法理解如何通过方程式。任何解决方案或指针都会得到极大的应用。谢谢

关于 Python 变量和用于变量的 SymPy 对象(符号),这里有几层潜在的混淆。

这是你所说的例子:

# 3 variables
syms = x, y, z = var('x:z')
# 2 values
vals = {x:1, y:2}
# an equations
eq = Eq(x, y/z)

# solve for the missing value symbolically
missing = set(syms) - set(vals)  # == {z}
solve(eq, missing)
[y/x]

# solve for the missing value after substituting in the known values
solve(eq.subs(vals))
[2]

您可以让求解器接受一个方程,然后指定值并计算出缺失的一个和 return 该值,方法如下:

>>> def solver(eq, **vals):
...     from sympy.core.containers import Dict
...     from sympy.solvers.solvers import solve
...     free = eq.free_symbols
...     vals = Dict(vals)
...     x = free - set(vals)
...     if len(x) != 1:
...         raise ValueError('specify all but one of the values for %s' % free)
...     x = x.pop()
...     return solve(eq.subs(vals), x, dict=True)
...
>>> solver(eq, x=1, z=2)
[{y: 2}]

这是否给了您一些关于如何继续的想法?