有没有办法在SymPy中处理常量函数参数? [英] Is there a way to handle constant function parameters in SymPy?
问题描述
我正在生成符号函数,并使用SymPy对其进行简化. 现在,我想一种简化"符号的方法,这些符号代表尚未安装的函数中的常量参数. 例如,如果我正在生成多项式,则可能会生成这样的字符串
I am generating symbolic functions and using SymPy to simplify them. Now I would like a way to "simplify" symbols that represent constant parameters in a function that is yet to be fitted. For example, if I am generating a polynomial, I might generate a string like this
C*x*x + C*x + C*x + C,
SymPy将变成哪个
which SymPy would turn into
C*x^2 + 2*C*x + C.
现在,我想找到一种方法来获取此信息:
Now I would like to find a way to get this:
C*x^2 + C*x + C.
换句话说,有一种方法可以告诉SymPy某个符号是常量且未定义,因此
In other words, is there a way to tell SymPy that a certain symbol is constant and undefined, so that
C+C -> C, C*C -> C, etc. Or more generally: f(C) = C, for any f(C)?
我的第一个想法是,也许有一个描述此属性的假设(例如Q.positive),我也许可以使用优化.但是,事实似乎并非如此. 如果没有别的,我敢肯定有一种方法可以使用preorder_traversal来完成我想要的事情,但是我无法提出一种实现它的策略. 任何帮助或想法都将受到赞赏.
My first idea was that perhaps there is an assumption (such as Q.positive) that describes this property and I might be able to use refine. However, this does not seem to be the case. If nothing else, I'm sure there is a way to use preorder_traversal to do what I want, but I can't come up with a strategy to do it. Any help or ideas are appreciated.
推荐答案
也许是这样(适用于已完全展开的表达式):
Perhaps something like this (applied to an expression that has been fully expanded):
def consim(eq, *v):
con = numbered_symbols('c', cls=Dummy)
reps = {}
for i in preorder_traversal(eq):
if i.is_Mul or i.is_Add:
c, d = i.as_independent(*v)
if c != i.identity and c.free_symbols:
c = reps.setdefault(c, next(con))
return eq.subs(reps)
>>> from sympy.abc import a, b, c, d, x
>>> eq = 2*a*x**2 + b*c*x + d + e
>>> consim(eq, x)
2
c₀ + c₁⋅x + c₂⋅x
您可能希望编号符号,但并非所有符号都相同.
You probably want numbered symbols, not all symbols the same.
这篇关于有没有办法在SymPy中处理常量函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!