Blanks in the denominator of a replacement rule - wolfram-mathematica

Mathematica 7.0 seems to dislike having blanks in the denominator. Can anyone explain why this is?
Input:
ClearAll["Global`*"];
(*Without blanks:*)
a^2 / b^2 /. a^2 / b^2 -> d
(*with:*)
a^2 / b^2 /. a^c_ / b^c_ -> d
(*Without blanks:*)
a^2 / b^2 /. (a / b)^2 -> d
(*With:*)
a^2 / b^2 /. (a / b)^c_ -> d
(*Without blanks:*)
a^2 / b^2 /. a^2 * b^(-2) -> d
(*With:*)
a^2 / b^2 /. a^c_ * b^(-c_) -> d
Output:
d
a^2/b^2
d
a^2/b^2
d
a^2/b^2
I'm trying to work this for a more complicated problem. The substitution that I want to make is in an expression of the form:
(a ^ c_. * Coefficient1_. / b ^ c_. / Coefficient2_.) + (a ^ d_. * Coefficient3_. / b ^ d_. / Coefficient4_.)
Where the coefficients may involve sums, products, and quotients of variables that may or may not includea and b.
Possibly relevant:
The FullForm shows that the power in the denominator is stored as a product of -1 and c:
Input:
FullForm[a^2/b^2]
FullForm[a^c_/b^c_]
FullForm[ (a / b)^2 ]
FullForm[(a / b)^c_ ]
FullForm[a^2 * b^(-2) ]
FullForm[a^c_ * b^(-c_)]
Output:
Times[Power[a,2],Power[b,-2]]
Times[Power[a,Pattern[c,Blank[]]],Power[b,Times[-1,Pattern[c,Blank[]]]]]
Times[Power[a,2],Power[b,-2]]
Power[Times[a,Power[b,-1]],Pattern[c,Blank[]]]
Times[Power[a,2],Power[b,-2]]
Times[Power[a,Pattern[c,Blank[]]],Power[b,Times[-1,Pattern[c,Blank[]]]]]
Edit: Bolded change to my actual case.

Generally speaking you should try to avoid doing mathematical manipulation using ReplaceAll which is a structural tool.
As opposed to FullForm, I will use TreeForm to illustrate these expressions:
a^2/b^2 // TreeForm
a^c_/b^c_ // TreeForm
You can see that while these expressions are mathematically similar, they are structurally quite different. You may be able to hammer out a functioning replacement rule for a specific case, but you will usually be better off using the Formula Manipulation (or Polynomial Algebra) tools that Mathematica provides.
If you carefully describe the mathematical manipulation you wish to achieve, I will attempt to provide a better solution.
As belisarius humorously points out in a comment, trying to force Mathematica to "see" or display expressions the way you do is often largely futile. This is one of the reasons that the opening statement above is true.

I agree with everything Mr.Wizard wrote. Having said that, a replacement rule that would work in this specific case would be:
a^2/b^2 /. (Times[Power[a,c_],Power[b,e_]]/; e == -c )-> d
or
a^2/b^2 /. (a^c_ b^e_/; e == -c )-> d
Note that I added the constraint /; e == -c so that I effectively have a -c_ without actually creating the corresponding Times[-1,c_] expression

The primary reason a^2 / b^2 /. a^c_ / b^c_ -> d doesn't work is your using Rule (->) not RuleDelayed (:>). The second reason, as you found with FullForm, is that a/b is interpreted as Times[a, Power[b,-1]], so it is best to not use division. Making these changes,
a^2 / b^2 /. a^n_ b^m_ :> {n,m}
returns {2, -2}. Usually, you'll want to have a default value, so that
a / b^2 /. a^n_. b^m_. :> {n,m}
returns {1,-2}.
Edit: to ensure that the two exponents are equal, requires the addition of the Condition (/;)
a^2 / b^2 /. a^n_. b^m_. /; n == m :> n
Note: by using _. this will also catch a/b.

Related

How to replace implicit subexpressions in Mathematica?

I have this expression in Mathematica:
(a^2 (alpha + beta)^2)/(b^2 + c^2) + (a (alpha + beta))/(b^2 + c^2) + 1
As you can see, the expression has a couple of subexpressions that repeat throughout it.
I want to be able to replace a/(b^2+c^2) with d and alpha+beta with gamma.
The final expression should then be:
1+d*gamma+a*d*gamma^2
I have much more complicated expressions where being able to do this would greatly simplify my work.
I have tried Googling this question, and I only find answers that use FactorTerms and ReplaceRepeated, but do not work consistently and for a more complicated expression like this one. I am hoping that someone here has the answer.
The hard part for the case at hand is the rule for d. Perhaps, there are simpler ways to do it, but one way is to expand the powers to products, to make it work. Let's say this is your expression:
expr = (a^2 (alpha + beta)^2)/(b^2 + c^2) + (a (alpha + beta))/(b^2 + c^2) + 1
and these are the rules one would naively write:
rules = {a/(b^2 + c^2) -> d, alpha + beta -> gamma}
What we would like to do now is to expand powers to products, in both expr and rules. The problem is that even if we do, they will auto-evaluate back to powers. To prevent that, we'll need to wrap them into, for example, Hold. Here is a function which will help us:
Clear[withExpandedPowers];
withExpandedPowers[expr_, f_: Hold] :=
Module[{times},
Apply[f,
Hold[expr] /. x_^(n_Integer?Positive) :>
With[{eval = times ## Table[x, {n}]}, eval /; True] /.
times -> Times //.
HoldPattern[Times[left___, Times[middle__], right___]] :>
Times[left, middle, right]]];
For example:
In[39]:= withExpandedPowers[expr]
Out[39]= Hold[1+(a (alpha+beta))/(b b+c c)+((alpha+beta) (alpha+beta) a a)/(b b+c c)]
The following will then do the job:
In[40]:=
ReleaseHold[
withExpandedPowers[expr] //.
withExpandedPowers[Map[MapAt[HoldPattern, #, 1] &, rules], Identity]]
Out[40]= 1 + d gamma + a d gamma^2
We had to additionally wrap the l.h.s. of rules in HoldPattern, to prevent products from collapsing back to powers there.
This is just one case where we had to fight the auto-simplification mechanism of Mathematica, but for this sort of problems this will be the main obstacle. I can't assess how robust this will be for larger and more complex expressions.
Using ReplaceRepeated:
(a^2 (alpha + beta)^2)/(b^2 + c^2) + (a (alpha + beta))/(b^2 + c^2) +
1 //. {a/(b^2 + c^2) -> d, alpha + beta -> gamma}
Or using TransformationFunctions:
FullSimplify[(a^2 (alpha + beta)^2)/(b^2 +
c^2) + (a (alpha + beta))/(b^2 + c^2) + 1,
TransformationFunctions -> {Automatic, # /.
a/(b^2 + c^2) -> d &, # /. alpha + beta -> gamma &}]
Both give:
1 + gamma (d + (a^2 gamma)/(b^2 + c^2))
I modestly --- I am not a computer scientist --- think this is simpler than all other proposed solutions
1+a(alpha+beta)/(b^2 + c^2) +a^2(alpha+beta)^2/(b^2 + c^2) \\.
{a^2-> a z, a/(b^2 + c^2)-> d,alpha+\beta -> gamma,z-> a}

how to simplify / expand / apply a pattern to a function's argument

(I made some changes...)
very often I want to simplify the function's argument, or apply a pattern to it, eg. I want to change:
Exp[a(b+c)]
into
Exp[a b + a c]
simple pattern doesn't help:
Sin[a(b+c)] /. Sin[aaa_] -> Sin[Expand[aaa]]
gives again
Sin[a(b+c)]
However, with functions other than Simplify / Expand it seems to do what I expect:
Sin[a (b + c)] /. Sin[aaa_] -> Sin[f[aaa]]
gives
Sin[ f[a(b+c)] ]
My usual solution was to use 2 patterns and Hold:
(Exp[a(b+c)] /. Exp[aaa_] -> Exp[Hold[ Expand[aaa] ]] ) /. Hold[xxx_] -> xxx
which results in
E^(a*b + a*c)
The disadvantage of this method is that code gets more complicated than it's neccesary.
MY REAL LIFE EXAMPLE is:
ppp2 =
( ppp1
/. { ExpIntegralEi[aaa_] ->
ExpIntegralEi[Hold[aaa /. { u2 -> 0, w2 -> 0, u3 -> x, w3 -> x}]],
Log[aaa_] ->
Log[Hold[aaa /. {u2 -> 0, w2 -> 0, u3 -> x, w3 -> x}]]
}
) /. Hold[xxx_] -> xxx;
where ppp1 is a long sum of terms containing u2, w2, u3, w3 and so on. I want to change the values of u, w2... ONLY in ExpIntegral and Log.
My other solution is a function:
ExpandArgument[expr_, what_] := Module[{list},
list = Extract[expr, Position[ expr, what[_] ]];
list = Map[Rule[#, what[Expand[ #[[1]] ]]] &, list];
Return[expr /. list]
]
The function I wrote can be easily generalised to make it possible to use not only Expand but also Simplify and so on:
ApplyToArgument[expr_, ToWhat_, WhatFunction_] := Module[{list},
list = Extract[expr, Position[ expr, ToWhat[_] ]];
list = Map[Rule[#, ToWhat[WhatFunction[ #[[1]] ]]] &, list];
Return[expr /. list]
]
For example:
ApplyToArgument[Sin[a (b + c)], Sin, Expand]
gives
Sin[a b + a c]
and
ApplyToArgument[Sin[a b + a c ], Sin, Simplify]
gives
Sin[a (b + c)]
This solution is easy to read but needs some refinement before being applied to many-argument functions (and I need these functions).
I guess I'm missing something fundamental about patterns in mathematica... How should I apply patterns to arguments of functions? (Or simplify, expand, etc. them)
Thanks a lot!
For the first part of the question, you could consider using RuleDelayed:
Sin[a (b + c)] /. Sin[aaa_] :> Sin[Expand[aaa]]
gives
Sin[a b + a c]
Use :> instead of ->. With ->, the right hand side is immediately evaluated, and only then applied. Expansion of aaa of course gives just aaa, and therefore evaluation of Sin[Expand[aaa]] gives Sin[aaa], thus the rule asks for replacing each application of Sin by itself. Then you also should not need those Hold constructs.
In a related note: Instead of applying the rule Hold[xxx_]->xxx, you can just pass your expression to ReleaseHold, for example ReleaseHold[Hold[1+1] /. 1->2] gives 4.
Also consider using ExpandAll:
ExpandAll[Exp[a (b + c)]] // FullForm
will give:
Power[E, Plus[Times[a, b], Times[a, c]]]
(This will turn Exp[...] into E^... though)
This is not a direct answer (others provided that), but for these kinds of manipulations the Algebraic Manipulation Palette (Palettes -> Other) is often quite convenient:
The disadvantage is that unlike typed-in commands, this operation won't be "recorded" and saved in the notebook.

Get mathematica to simplify expression with another equation

I have a very complicated mathematica expression that I'd like to simplify by using a new, possibly dimensionless parameter.
An example of my expression is:
K=a*b*t/((t+f)c*d);
(the actual expression is monstrously large, thousands of characters). I'd like to replace all occurrences of the expression t/(t+f) with p
p=t/(t+f);
The goal here is to find a replacement so that all t's and f's are replaced by p. In this case, the replacement p is a nondimensionalized parameter, so it seems like a good candidate replacement.
I've not been able to figure out how to do this in mathematica (or if its possible). I tried:
eq1= K==a*b*t/((t+f)c*d);
eq2= p==t/(t+f);
Solve[{eq1,eq2},K]
Not surprisingly, this doesn't work. If there were a way to force it to solve for K in terms of p,a,b,c,d, this might work, but I can't figure out how to do that either. Thoughts?
Edit #1 (11/10/11 - 1:30)
[deleted to simplify]
OK, new tact. I've taken p=ton/(ton+toff) and multiplied p by several expressions. I know that p can be completely eliminated. The new expression (in terms of p) is
testEQ = A B p + A^2 B p^2 + (A+B)p^3;
Then I made the substitution for p, and called (normal) FullSimplify, giving me this expression.
testEQ2= (ton (B ton^2 + A^2 B ton (toff + ton) +
A (ton^2 + B (toff + ton)^2)))/(toff + ton)^3;
Finally, I tried all of the suggestions below, except the last (not sure how it works yet!)
Only the eliminate option worked. So I guess I'll try this method from now on. Thank you.
EQ1 = a1 == (ton (B ton^2 + A^2 B ton (toff + ton) +
A (ton^2 + B (toff + ton)^2)))/(toff + ton)^3;
EQ2 = P1 == ton/(ton + toff);
Eliminate[{EQ1, EQ2}, {ton, toff}]
A B P1 + A^2 B P1^2 + (A + B) P1^3 == a1
I should add, if the goal is to make all substitutions that are possible, leaving the rest, I still don't know how to do that. But it appears that if a substitution can completely eliminate a few variables, Eliminate[] works best.
Have you tried this?
K = a*b*t/((t + f) c*d);
Solve[p == t/(t + f), t]
-> {{t -> -((f p)/(-1 + p))}}
Simplify[K /. %[[1]] ]
-> (a b p)/(c d)
EDIT: Oh, and are you aware of Eliminiate?
Eliminate[{eq1, eq2}, {t,f}]
-> a b p == c d K && c != 0 && d != 0
Solve[%, K]
-> {{K -> (a b p)/(c d)}}
EDIT 2: Also, in this simple case, solving for K and t simultaneously seems to do the trick, too:
Solve[{eq1, eq2}, {K, t}]
-> {{K -> (a b p)/(c d), t -> -((f p)/(-1 + p))}}
Something along these lines is discussed in the MathGroup post at
http://forums.wolfram.com/mathgroup/archive/2009/Oct/msg00023.html
(I see it has an apocryphal note that is quite relevant, at least to the author of that post.)
Here is how it might be applied in the example above. For purposes of keeping this self contained I'll repeat the replacement code.
replacementFunction[expr_, rep_, vars_] :=
Module[{num = Numerator[expr], den = Denominator[expr],
hed = Head[expr], base, expon},
If[PolynomialQ[num, vars] &&
PolynomialQ[den, vars] && ! NumberQ[den],
replacementFunction[num, rep, vars]/
replacementFunction[den, rep, vars],
If[hed === Power && Length[expr] == 2,
base = replacementFunction[expr[[1]], rep, vars];
expon = replacementFunction[expr[[2]], rep, vars];
PolynomialReduce[base^expon, rep, vars][[2]],
If[Head[hed] === Symbol &&
MemberQ[Attributes[hed], NumericFunction],
Map[replacementFunction[#, rep, vars] &, expr],
PolynomialReduce[expr, rep, vars][[2]]]]]]
Your example is now as follows. We take the input, and also the replacement. For the latter we make an equivalent polynomial by clearing denominators.
kK = a*b*t/((t + f) c*d);
rep = Numerator[Together[p - t/(t + f)]];
Now we can invoke the replacement. We list the variables we are interested in replacing, treating 'p' as a parameter. This way it will get ordered lower than the others, meaning the replacements will try to remove them in favor of 'p'.
In[127]:= replacementFunction[kK, rep, {t, f}]
Out[127]= (a b p)/(c d)
This approach has a bit of magic in figuring out what should be the listed "variables". Possibly some further tweakage could be done to improve on that. But I believe that, generally, simply not listing the things we want to use as new replacements is the right way to go.
Over the years there have been variants of this idea on MathGroup. It is possible that some others may be better suited to the specific expression(s) you wish to handle.
--- edit ---
The idea behind this is to use PolynomialReduce to do algebraic replacement. That is to say, we do not try for pattern matching but instead use polynomial "canonicalization" a method. But in general we're not working with polynomial inputs. So we apply this idea recursively on PolynomialQ arguments inside NumericQ functions.
Earlier versions of this idea, along with some more explanation, can be found at the note referenced below, as well as in notes it references (how's that for explanatory recursion?).
http://forums.wolfram.com/mathgroup/archive/2006/Aug/msg00283.html
--- end edit ---
--- edit 2 ---
As observed in the wild, this approach is not always a simplifier. It does algebraic replacement, which involves, under the hood, a notion of "term ordering" (roughly, "which things get replaced by which others?") and thus simple variables may expand to longer expressions.
Another form of term rewriting is syntactic replacement via pattern matching, and other responses discuss using that approach. It has a different drawback, insofar as the generality of patterns to consider might become overwhelming. For example, what does one do with k^2/(w + p^4)^3 when the rule is to replace k/(w + p^4) with q? (Specifically, how do we recognize this as being equivalent to (k/(w + p^4))^2*1/(w + p^4)?)
The upshot is one needs to have an idea of what is desired and what methods might be feasible. This of course is generally problem specific.
One thing that occurs is perhaps you want to find and replace all commonly occurring "complicated" expressions with simpler ones. This is referred to as common subexpression elimination (CSE). In Mathematica this can be done using a function called Experimental`OptimizeExpression[]. Here are several links to MathGroup posts that discuss this.
http://forums.wolfram.com/mathgroup/archive/2009/Jul/msg00138.html
http://forums.wolfram.com/mathgroup/archive/2007/Nov/msg00270.html
http://forums.wolfram.com/mathgroup/archive/2006/Sep/msg00300.html
http://forums.wolfram.com/mathgroup/archive/2005/Jan/msg00387.html
http://forums.wolfram.com/mathgroup/archive/2002/Jan/msg00369.html
Here is an example from one of those notes.
InputForm[Experimental`OptimizeExpression[(3 + 3*a^2 + Sqrt[5 + 6*a + 5*a^2] +
a*(4 + Sqrt[5 + 6*a + 5*a^2]))/6]]
Out[206]//InputForm=
Experimental`OptimizedExpression[Block[{Compile`$1, Compile`$3, Compile`$4,
Compile`$5, Compile`$6}, Compile`$1 = a^2; Compile`$3 = 6*a;
Compile`$4 = 5*Compile`$1; Compile`$5 = 5 + Compile`$3 + Compile`$4;
Compile`$6 = Sqrt[Compile`$5]; (3 + 3*Compile`$1 + Compile`$6 +
a*(4 + Compile`$6))/6]]
--- end edit 2 ---
Daniel Lichtblau
K = a*b*t/((t+f)c*d);
FullSimplify[ K,
TransformationFunctions -> {(# /. t/(t + f) -> p &), Automatic}]
(a b p) / (c d)
Corrected update to show another method:
EQ1 = a1 == (ton (B ton^2 + A^2 B ton (toff + ton) +
A (ton^2 + B (toff + ton)^2)))/(toff + ton)^3;
f = # /. ton + toff -> ton/p &;
FullSimplify[f # EQ1]
a1 == p (A B + A^2 B p + (A + B) p^2)
I don't know if this is of any value at this point, but hopefully at least it works.

Weird behaviour with GroebnerBasis in v7

I came across some weird behaviour when using GroebnerBasis. In m1 below, I used a Greek letter as my variable and in m2, I used a Latin letter. Both of them have no rules associated with them. Why do I get vastly different answers depending on what variable I choose?
Image:
Copyable code:
Clear["Global`*"]
g = Module[{x},
x /. Solve[
z - x (1 - b -
b x ( (a (3 - 2 a (1 + x)))/(1 - 3 a x + 2 a^2 x^2))) == 0,
x]][[3]];
m1 = First#GroebnerBasis[\[Kappa] - g, z]
m2 = First#GroebnerBasis[k - g, z]
EDIT:
As pointed out by belisarius, my usage of GroebnerBasis is not entirely correct as it requires a polynomial input, whereas mine is not. This error, introduced by a copy-pasta, went unnoticed until now, as I was getting the answer that I expected when I followed through with the rest of my code using m1 from above. However, I'm not fully convinced that it is an unreasonable usage. Consider the example below:
x = (-b+Sqrt[b^2-4 a c])/2a;
p = First#GroebnerBasis[k - x,{a,b,c}]; (*get relation or cover for Riemann surface*)
q = First#GroebnerBasis[{D[p,k] == 0, p == 0},{a,b,c},k,
MonomialOrder -> EliminationOrder];
Solve[q==0, b] (*get condition on b for double root or branch point*)
{{b -> -2 Sqrt[a] Sqrt[c]}, {b -> 2 Sqrt[a] Sqrt[c]}}
which is correct. So my interpretation is that it is OK to use GroebnerBasis in such cases, but I'm not all too familiar with the deep theory behind it, so I could be completely wrong here.
P.S. I heard that if you mention GroebnerBasis three times in your post, Daniel Lichtblau will answer your question :)
The bug that was shown by these examples will be fixed in version 9. Offhand I do not know how to evade it in versions 8 and prior. If I recall correctly it was caused by an intermediate numeric overflow in some code that was checking whether a symbolic polynomial coefficient might be zero.
For some purposes it might be suitable to specify more variables and possibly a non-default term order. Also clearing denominators can be helpful at least in cases where that is a valid thing to do. That said, I do not know if these tactics would help in this example.
I'll look some more at this code but probably not in the near future.
Daniel Lichtblau
This may be related to the fact that Mathematica does not try all variable orders in functions like Simplify. Here is an example:
ClearAll[a, b, c]
expr = (c^4 b^2)/(c^4 b^2 + a^4 b^2 + c^2 a^2 (1 - 2 b^2));
Simplify[expr]
Simplify[expr /. {a -> b, b -> a}]
(b^2 c^4)/(a^4 b^2 + a^2 (1 - 2 b^2) c^2 + b^2 c^4)
(a^2 c^4)/(b^2 c^2 + a^2 (b^2 - c^2)^2)
Adam Strzebonski explained that:
...one can try FullSimplify with all
possible orderings of chosen
variables. Of course, this multiplies
the computation time by
Factorial[Length[variables]]...

How do I force Mathematica to include user defined functions in Simplify and FullSimplify?

Let's say I have a relation r^2 = x^2 + y^2. Now suppose after a calculation i get a complicated output of x and y, but which could in theory be simplified a lot by using the above relation. How do I tell Mathematica to do that?
I'm referring to situations where replacement rules x^2+y^2 -> r^2 and using Simplify/FullSimplify with Assumptions won't work, e.g. if the output is x/y + y/x = (x^2+y^2)/(xy) = r^2/(xy).
Simplification works really well with built in functions but not with user defined functions! So essentially I would like my functions to be treated like the built in functions!
I believe you are looking for TransformationFunctions.
f = # /. x^2 + y^2 -> r^2 &;
Simplify[x/y + y/x, TransformationFunctions -> {Automatic, f}]
(* Out= r^2/(x y) *)
In the example you give
(x/y + y/x // Together) /. {x^2 + y^2 -> r^2}
==> r^2/(x y)
works. But I've learned that in many occasions replacements like this don't work. A tip I once got was to replace this replacement with one which has a more simpler LHS like: x^2 -> r^2-y^2 (or even x->Sqrt[r^2-y^2] if you know that the values of x and y allow this).

Resources