gpt4 book ai didi

python - 在 sympy 中,我如何获得有理表达式的系数?

转载 作者:行者123 更新时间:2023-11-28 16:22:20 24 4
gpt4 key购买 nike

我有一个有理数(此处为双线性)表达式,希望我能收集系数。但是如何呢?

from sympy import symbols, Wild, pretty_print

a, b, c, d, x, s = symbols("a b c d x s")

def coeffs(expr):
n0 = Wild("n0", exclude=[x])
n1 = Wild("n1", exclude=[x])
d0 = Wild("d0", exclude=[x])
d1 = Wild("d1", exclude=[x])
match = expr.match((n0 + n1*x) / (d0 + d1*x))
n0 = n0.xreplace(match)
n1 = n1.xreplace(match)
d0 = d0.xreplace(match)
d1 = d1.xreplace(match)
return [n0, n1, d0, d1]

if __name__ == '__main__':
pretty_print(coeffs((a + b*x) / (c + d*x)))
pretty_print(coeffs(2 * (a + b*x) / (c + d*x)))
pretty_print(coeffs(s * (a + b*x) / (c + d*x)))

我尝试使用 match 进行此操作,但它几乎总是失败,例如在最后一行(带有符号前置因子“s”的那一行)我得到了

Traceback (most recent call last):
File "...", line 20, in <module>
pretty_print(coeffs(s * (a + b*x) / (c + d*x)))
File "...", line 11, in coeffs
n0 = n0.xreplace(match)
File "/usr/lib/python3/dist-packages/sympy/core/basic.py", line 1626, in xreplace
return rule.get(self, self)
AttributeError: 'NoneType' object has no attribute 'get'

所以匹配失败。

最佳答案

如果您知道要考虑的表达式是有理数,则可以提取它们的分子和分母并独立地求出它们的系数。

这是一种方法:

import sympy as sp

def get_rational_coeffs(expr):
num, denom = expr.as_numer_denom()

return [sp.Poly(num, x).all_coeffs(), sp.Poly(denom, x).all_coeffs()]

a, b, c, d, x, s = sp.symbols("a b c d x s")
expr = (a + b*x) / (c + d*x)

# note the order of returned coefficients
((n1, n0), (d1, d0)) = get_rational_coeffs(s*expr)
print(((n0, n1), (d0, d1)))

((a*s, b*s), (c, d))

上述方法也比 coeffs 更快。对于需要 expr 系数的情况(coeffs 成功的情况),我得到以下时间(基于 Jupyter 的 %timeit 魔法) :

%timeit get_rational_coeffs(expr)
%timeit coeffs(expr)

1000 loops, best of 3: 1.33 ms per loop

1000 loops, best of 3: 1.99 ms per loop

关于python - 在 sympy 中,我如何获得有理表达式的系数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com