Skip to main content
 首页 » 编程设计

python之使用 SymPy 消除变量以关联 Python 中的两个函数

2025年05月04日20pengyingh

我有两个由变量“t”参数化的方程式。这些看起来像:

X = p(t)  
Y = q(t) 

其中 p 和 q 是 t 中的多项式。我想使用 Python 的 SymPy 库来消除 t 变量并为某些函数 X 表达 Y = F(X)。我尝试在 SymPy 中使用 solve() 但这不是很好。我知道 Maple 和 Mathematica 都有可以完成此操作的 eliminate() 函数,但我想知道 Python 是否可能具有执行此操作的通用函数。

请您参考如下方法:

这是一个经过轻微测试的简单例程

def eliminate(eqs, z): 
    """return eqs with parameter z eliminated from each equation; the first 
    element in the returned list will be the definition of z that was used 
    to eliminate z from the other equations. 
 
    Examples 
    ======== 
 
    >>> eqs = [Eq(2*x + 3*y + 4*z, 1), 
    ...        Eq(9*x + 8*y + 7*z, 2)] 
    >>> eliminate(eqs, z) 
    [Eq(z, -x/2 - 3*y/4 + 1/4), Eq(11*x/2 + 11*y/4 + 7/4, 2)] 
    >>> Eq(y,solve(_[1], y)[0]) 
    Eq(y, -2*x + 1/11) 
    """ 
    from sympy.solvers.solveset import linsolve 
    Z = Dummy() 
    rv = [] 
    for i, e in enumerate(eqs): 
        if z not in e.free_symbols: 
            continue 
        e = e.subs(z, Z) 
        if z in e.free_symbols: 
            break 
        try: 
            s = linsolve([e], Z) 
            if s: 
                zi = list(s)[0][0] 
                rv.append(Eq(z, zi)) 
                rv.extend([eqs[j].subs(z, zi) 
                    for j in range(len(eqs)) if j != i]) 
                return rv 
        except ValueError: 
            continue 
    raise ValueError('only a linear parameter can be eliminated') 

在 this issue 处有一个更复杂的例程.