Extracting an expression matching a pattern from a large expression

人盡茶涼 提交于 2019-12-03 09:40:46

问题


I have a Mathematica expression that contains a single square root, schematically

expr = a / (b + Sqrt[c]);

where a,b,c are large expressions. I would like to extract the expression under the sqrt, for instance by matching to a pattern, something like

Match[expr,Sqrt[x_]] // should return c

Is there an easy way to do this?


回答1:


Theoretically, this should work correctly:

extractSqrt = Cases[ToBoxes@#, SqrtBox@x_ :> ToExpression@x, Infinity] &;

extractSqrt[expr]



回答2:


If you are willing to change the assignment to expr, you can do this:

expr = Hold[a / (b + Sqrt[c])];

Cases[expr, HoldPattern @ Sqrt[x_] :> x, Infinity]

The Hold in the assignment statement prevents Mathematica from applying any simplifications to the expression. In this case, Sqrt[c] gets "simplified" into Power[c,Rational[1,2]].

The HoldPattern is essential in the Cases expression to prevent the same simplification from happening to the pattern being matched.




回答3:


I await a few examples, but in the meantime, try:

Cases[expr, x_^(1/2 | -1/2) :> x, Infinity]

The standard internal form for Sqrt(x) is Power[x, 1/2].



来源:https://stackoverflow.com/questions/5682963/extracting-an-expression-matching-a-pattern-from-a-large-expression

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