Is there a way to handle constant function parameters in SymPy?

一个人想着一个人 提交于 2020-04-14 07:34:42

问题


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,

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.

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)?

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.


回答1:


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.



来源:https://stackoverflow.com/questions/60975229/is-there-a-way-to-handle-constant-function-parameters-in-sympy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!