python - sympy:规范化右侧为常数的线性等式

标签 python math sympy

我正在尝试找到一种合适的方法(使用 sympy)来规范化右侧常量的线性等式。例如:

x + 1 = y

变成:

x - y = -1

这是我相当老套的解决方案:

def canonical_linear(f):
""" canonicalise a linear equality """

    lhs = f.lhs - f.rhs
    const_l = [ x for x in lhs.as_ordered_terms() if x.is_number ]

    if len(const_l) == 0:
        const = 0
    elif len(const_l) == 1:
        const = const_l[0]
    else:
        raise NotImplementedError("SHIT")

    return sympy.Eq(lhs - const, -const)

这个可以改进吗?干杯?

最佳答案

这是来自 SymPy 中 solve 例程的源代码:

1262         if all(p.is_linear for p in polys):
1263             n, m = len(polys), len(symbols)
1264             matrix = zeros(n, m + 1)
1265 
1266             for i, poly in enumerate(polys):
1267                 for monom, coeff in poly.terms():
1268                     try:
1269                         j = list(monom).index(1)
1270                         matrix[i, j] = coeff
1271                     except ValueError:
1272                         matrix[i, m] = -coeff
1273 
1274             # returns a dictionary ({symbols: values}) or None
1275             result = solve_linear_system(matrix, *symbols, **flags)

它将每个方程转换为多项式(Poly 是 SymPy 中的一个类,用于高效处理多项式),如果多项式是线性的,它会遍历它以构造要求解的矩阵(最后一列是自由系数)。

上面的代码没有显示到多项式的转换。多项式在 polys 中,自由符号在 symbols 中。

关于python - sympy:规范化右侧为常数的线性等式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147966/

相关文章:

Python - 如何更新多维字典

python - 模型的准确度是 0.86 而 AUC 是 0.50?

python - 如何使用 Python 解析无限滚动页面(例如 Wallbase.cc/search/sky)?

algorithm - 点在多段线的哪一侧

python - 使用 as_strided 分割 numpy 数组

c# - 计算两个时间跨度DSP之间的差

math - 这是什么类型的数学 : a -> b -> c

python - sympy的QRsolve方法从不返回或抛出 "Could not normalize the vector"错误

python - cosd 和 sind 与 sympy

python - 如何评估 SymPy 在初始条件下给出的常数?