Maxima: how to replace common subexpressions with symbols

血红的双手。 提交于 2019-12-09 06:31:29

问题


Suppose I have an expression like (actually mine is much more complex, thousands of characters)

expr:a+b*c+b*c*d;

and I want to replace an internal sub-expression with a symbol (useful to avoid recomputation of common subexpressions), say k in place of b*c:

subst(b*c=k,expr);

returns

k+b*c*d+a

How I can make Maxima calculate the "right" substitution so to return (apart from obviuos simplification, here)

k+k*d+a

?


回答1:


Take a look at let and letsimp. E.g.:

(%i2) expr : a + b*c + b*c*d;
(%o2) b*c*d+b*c+a
(%i3) let (b*c, k);
(%o3) b*c --> k
(%i4) letsimp (expr);
(%o4) d*k+k+a

letsimp differs from subst and tellsimp or defrule in that those other functions make only formal substitutions, i.e., replacing subexpressions which are exactly the same as some pattern.




回答2:


You can try optimize

http://maxima.sourceforge.net/docs/manual/en/maxima_6.html#IDX219

(%i14) example(optimize);

(%i15) diff(exp(y+x^2)/(y+x),x,2)
                        2            2              2            2
               2   y + x        y + x          y + x        y + x
            4 x  %e         2 %e         4 x %e         2 %e
(%o15)      ------------- + ---------- - ------------ + ----------
                y + x         y + x               2             3
                                           (y + x)       (y + x)
(%i16) optimize(%)
                                                 2         y + %2       1
(%o16) block([%1, %2, %3, %4], %1 : y + x, %2 : x , %3 : %e      , %4 : --, 
                                                                        %1
                                                                 4 x %3   2 %3
                                          4 %2 %4 %3 + 2 %4 %3 - ------ + ----)
                                                                    2       3
                                                                  %1      %1


来源:https://stackoverflow.com/questions/22685853/maxima-how-to-replace-common-subexpressions-with-symbols

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