Mathematica: Using 'Refine' with an unsolvable integral - wolfram-mathematica

I would like Mathematica to tell me whether an integral is positive or negative, given a list of assumptions. I'm attempting to do this using the 'Refine' command. I was not getting the result I wanted, so I simplified my assumptions to the following:
Clear[part1a, M, l, phi];
part1a = Integrate[D[M[q,P,k,phi,w,L,t,f,l,s,r,y,b,h,c],l], {phi, 1.5, Infinity}]
Refine[part1a<0, {part1a<0}]
The function M[q,P,k,phi,w,L,t,f,l,s,r,y,b,h,c] isn't specified, neither is the value of phi. I was surprised when Mathematica was still unable to tell me whether this was true or false, given the assumption.
Why would this be? Is there a way to make Refine work with an integral like this? Is there another command that's more appropriate? Eventually I want to use my original list of assumptions, but it seems that first I need to figure out why Refine[part1a<0, {part1a<0}] doesn't even work.
If you do the same process with a cleared part1a, it works just fine:
Clear[part1a];
Refine[part1a<0, {part1a<0}]
You will get
Out= True

I assume your real problem is that unevaluated integral appears as part of a larger expression.. (otherwise its rather trivial). Anyway first note that Simplify works:
Simplify[ part1a < 0, Assumptions -> {part1a < 0}]
True
another trick is to first replace your expression with a symbol:
Refine[ (part1a /. part1a -> int) < 0, {int < 0}]
True

Related

Prolog why my function always evaluates to true

I have the folowing code
isInRange(Point1,Point2,Range):-
manhatan2(Point1,Point2,Manhatan),
Range>Manhatan.
manhatan2 computes the manhatan distance between 2 points give in as a 2 element list [X,Y]
I don't understand why isInRange always evaluates to true
isInRange([0,0],[0,10],9) evaluates to true
isInRange([0,0],[0,10],100) also evaluates to true
I am pretty sure i did the manhatan function right.Have tested it with many values
Can anyone help me understand what is wrong with my code ?
%Edit starts here
So i traced the damn thing and here is more code i use
modul(A,B,R):-A<B,R is B-A.
modul(A,B,R):-A>B,R is A-B.
extractFromList([H|_],X,R):- X is 0,R is H.
extractFromList([_|T],X,R):- X1 is X-1,extractFromList(T,X1,R).
manhatan(X1,Y1,X2,Y2,R):- modul(X1,X2,R1),modul(Y1,Y2,R2),R is R1+R2.
manhatan2(P1,P2,R):-
extractFromList(P1,0,X1),
extractFromList(P1,1,Y1),
extractFromList(P2,0,X2),
extractFromList(P2,1,Y2),
manhatan(X1,Y1,X2,Y2,R).
The extract fromFromList extracts the Xth element from the given list
modul should return |A-B|
Tracing isInRange([0,0],[0,10],100) everthing whent as i whanted.
Tracing isInRange([0,0],[0,10],9) stoped when comparing the manhatan with the range and
started redoing modul(0,10,_GXXX) evaluating _GXXX to -10 and thus the Manhatan < Range condition evaluated to true thus all isInRange evaluating to true
Why does it do that ?
Why does it redo the modul computation in this way ?
The short answer:
The following code does what you want:
manhattan(L1,L2,Result) :- manhattan(L1,L2,0,Result).
manhattan([],[],Res,Res).
manhattan([H1|T1],[H2|T2],Acc,Res) :-
AccNew is Acc + abs(H1-H2),
manhattan(T1,T2,AccNew,Res).
isInRange(P1, P2, Range) :-
manhattan(P1, P2, Distance),
Range > Distance.
Longer answer:
I tried your code and it doesn't behave as you describe it.
For me, isInRange always fails, because 'modul' fails if A==B.
You should change the test on the first case to A =< B.
Or, even better, use the builtin 'abs' function.
I assume that in your previous version you didn't have a test in the second case.
In that case Prolog will try the second case when the first case leads to failure (for example because Range > Manhatan fails).
Adding the test in the second case in one way to solve this problem.

picking specific symbol definitions in mathematica (not transformation rules)

I have a following problem.
f[1]=1;
f[2]=2;
f[_]:=0;
dvs = DownValues[f];
this gives
dvs =
{
HoldPattern[f[1]] :> 1,
HoldPattern[f[2]] :> 2,
HoldPattern[f[_]] :> 0
}
My problem is that I would like to extract only definitions for f[1] and f[2] etc but not the general definition f[_], and I do not know how to do this.
I tried,
Cases[dvs, HoldPattern[ f[_Integer] :> _ ]] (*)
but it gives me nothing, i.e. the empty list.
Interestingly, changing HoldPattern into temporary^footnote
dvs1 = {temporary[1] :> 1, temporary[2] :> 2, temporary[_] :> 0}
and issuing
Cases[dvs1, HoldPattern[temporary[_Integer] :> _]]
gives
{temporary[1] :> 1, temporary[2] :> 2}
and it works. This means that (*) is almost a solution.
I do not not understand why does it work with temporary and not with HoldPattern? How can I make it work directly with HoldPattern?
Of course, the question is what gets evaluated and what not etc. The ethernal problem when coding in Mathematica. Something for real gurus...
With best regards
Zoran
footnote = I typed it by hand as replacement "/. HoldPattern -> temporary" actually executes the f[_]:=0 rule and gives someting strange, this excecution I certainly would like to avoid.
The reason is that you have to escape the HoldPattern, perhaps with Verbatim:
In[11]:= Cases[dvs,
Verbatim[RuleDelayed][
Verbatim[HoldPattern][HoldPattern[f[_Integer]]], _]]
Out[11]= {HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2}
There are just a few heads for which this is necessary, and HoldPattern is one of them, precisely because it is normally "invisible" to the pattern-matcher. For your temporary, or other heads, this wouldn't be necessary. Note by the way that the pattern f[_Integer] is wrapped in HoldPattern - this time HoldPattern is used for its direct purpose - to protect the pattern from evaluation. Note that RuleDelayed is also wrapped in Verbatim - this is in fact another common case for Verbatim - this is needed because Cases has a syntax involving a rule, and we do not want Cases to use this interpretation here. So, this is IMO an overall very good example to illustrate both HoldPattern and Verbatim.
Note also that it is possible to achieve the goal entirely with HoldPattern, like so:
In[14]:= Cases[dvs,HoldPattern[HoldPattern[HoldPattern][f[_Integer]]:>_]]
Out[14]= {HoldPattern[f[1]]:>1,HoldPattern[f[2]]:>2}
However, using HoldPattern for escaping purposes (in place of Verbatim) is IMO conceptually wrong.
EDIT
To calrify a little the situation with Cases, here is a simple example where we use the syntax of Cases involving transformation rules. This extended syntax instructs Cases to not only find and collect matching pieces, but also transform them according to the rules, right after they were found, so the resulting list contains the transformed pieces.
In[29]:= ClearAll[a, b, c, d, e, f];
Cases[{a, b, c, d, e, f}, s_Symbol :> s^2]
Out[30]= {a^2, b^2, c^2, d^2, e^2, f^2}
But what if we need to find elements that are themselves rules? If we just try this:
In[33]:= Cases[{a:>b,c:>d,e:>f},s_Symbol:>_]
Out[33]= {}
It doesn't work since Cases interprets the rule in the second argument as an instruction to use extended syntax, find a symbol and replace it with _. Since it searches on level 1 by default, and symbols are on level 2 here, it finds nothing. Observe:
In[34]:= Cases[{a:>b,c:>d,e:>f},s_Symbol:>_,{2}]
Out[34]= {_,_,_,_,_,_}
In any case, this is not what we wanted. Therefore, we have to force Cases to consider the second argument as a plain pattern (simple, rather than extended, syntax). There are several ways to do that, but all of them "escape" RuleDelayed (or Rule) in some way:
In[37]:= Cases[{a:>b,c:>d,e:>f},(s_Symbol:>_):>s]
Out[37]= {a,c,e}
In[38]:= Cases[{a:>b,c:>d,e:>f},Verbatim[RuleDelayed][s_Symbol,_]:>s]
Out[38]= {a,c,e}
In[39]:= Cases[{a:>b,c:>d,e:>f},(Rule|RuleDelayed)[s_Symbol,_]:>s]
Out[39]= {a,c,e}
In all cases, we either avoid the extended syntax for Cases (last two examples), or manage to use it to our advantage (first case).
Leonid, of course, completely answered the question about why your temporary solution works but HoldPattern does not. However, as an answer to your original problem of extracting the f[1] and f[2] type terms, his code is a bit ugly. To solve just the problem of extracting these terms, I would just concentrate on the structure of the left-hand-side of the definition and use the fact that FreeQ searches at all levels. So, defining
f[1] = 1; f[2] = 2; f[_] := 0;
dvs = DownValues[f];
All of the following
Select[dvs, FreeQ[#, Verbatim[_]] &]
Select[dvs, FreeQ[#, Verbatim[f[_]]] &]
Select[dvs, ! FreeQ[#, HoldPattern[f[_Integer]]] &]
yield the result
{HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2}
Provided there are no f[...] (or, for the first version, Blank[]) terms on the right-hand-side of the downvalues of f, then one of the above will probably be suitable.
Based on Simon's excellent solution here, I suggest:
Cases[DownValues[f], _?(FreeQ[#[[1]], Pattern | Blank] &)]

Can I automatically lazily evaluate function parameters in Mathematica?

In Mathematica, I'd like to do something along the lines of:
f[Rational[a_, b_], Rational[c_, d_]] := {a+c, b+d}
But if I evaluate it with expressions of the following form I get the wrong result:
In: f[Rational[50, 100], Rational[4, 10]]
Out: {3, 7}
(* Expected: 54 / 110 -> 27 / 55 *)
Is there any way I can force Mathematica to stop simplifying the expression immediately? I can just do a hold on whatever I pass in, then have the function in question just call ReleaseHold[..] on whatever what was passed in.
This solution is very ugly though, and I don't want to have to do this. I know some functions in Mathematica automatically hold whatever is passed in and delay evaluating it for some reason or another, and I would like to do this here.
In short: How can I force Mathematica to lazily evaluate something being passed into a function without having to manually hold it?
In the standard evaluation procedure, each argument of a function is evaluated in turn. This is prevented by setting the attributes HoldFirst, HoldRest and HoldAll. These attributes make Mathematica "hold" particular arguments in an unevaluated form.
http://reference.wolfram.com/legacy/v5/TheMathematicaBook/PrinciplesOfMathematica/EvaluationOfExpressions/2.6.5.html
e.g.
SetAttributes[yourFunction, HoldFirst]
http://reference.wolfram.com/mathematica/ref/HoldFirst.html
The docs say any auto-Held arguments are automatically evaluated the first time you use them in the function body. However if for some reason you want to continue working with the argument in the Hold form (e.g. if you'd like to do pattern-matching and rewriting on the unevaluated form of the expression), then perhaps you can re-Hold it.
Using the HoldAll attribute ninjagecko mentioned I was able to craft a solution.
There was actually another issue going on that I wasn't able to see immediately. Specifically, my function wasn't pattern matching as I thought it would be.
I thought my initial issue was simply that Mathematica was automatically simplifying my expressions and I needed to lazily evaluate the parameters being passed in for the correct behavior.
In reality, I forgot that there are multiple ways of representing expressions in Mathematica. As a toy example consider the following function which extracts the numerator and denominator of a fraction:
ExtractNumDem[Fraction[a_, b_]] := {a, b}
(* Already incorrect, ExtractNumDem[4 / 100] gives {1, 25} *)
Just adding the HoldAll (Or HoldFirst even) attribute results in another issue:
SetAttributess[ExtractNumDem, HoldAll];
ExtractNumDem[4 / 100] (* Gives ExtractNumDem[4 / 100] *)
The expression 4 / 100 is actually evaluating to Times[4, Power[100, -1]]. To fix this second issue I had to add a definition for fractions that look like that:
ExtractNumDem[Times[a_, Power[b_, -1]] := {a, b}
ExtractNumDem[4/100] (* Now gives {4, 100} *)
My solution to fixing the issue in my original answer applied the same exact principle. Here's some code to actually see the issue I was running into:
ClearAll[ExtractNumDem]
ExtractNumDem[Rational[a_, b_]] := {a, b}
ExtractNumDem[4 / 100]
SetAttributes[ExtractNumDem, HoldAll];
ExtractNumDem[4 / 100]
ExtractNumDem[Times[a_, Power[b_, -1]]] := {a, b}
ExtractNumDem[4/100]

Problem performing a substitution in a multiple derivative

I have a basic problem in Mathematica which has puzzled me for a while. I want to take the m'th derivative of x*Exp[t*x], then evaluate this at x=0. But the following does not work correct. Please share your thoughts.
D[x*Exp[t*x], {x, m}] /. x -> 0
Also what does the error mean
General::ivar: 0 is not a valid variable.
Edit: my previous example (D[Exp[t*x], {x, m}] /. x -> 0) was trivial. So I made it harder. :)
My question is: how to force it to do the derivative evaluation first, then do substitution.
As pointed out by others, (in general) Mathematica does not know how to take the derivative an arbitrary number of times, even if you specify that number is a positive integer.
This means that the D[expr,{x,m}] command remains unevaluated and then when you set x->0, it's now trying to take the derivative with respect to a constant, which yields the error message.
In general, what you want is the m'th derivative of the function evaluated at zero.
This can be written as
Derivative[m][Function[x,x Exp[t x]]][0]
or
Derivative[m][# Exp[t #]&][0]
You then get the table of coefficients
In[2]:= Table[%, {m, 1, 10}]
Out[2]= {1, 2 t, 3 t^2, 4 t^3, 5 t^4, 6 t^5, 7 t^6, 8 t^7, 9 t^8, 10 t^9}
But a little more thought shows that you really just want the m'th term in the series, so SeriesCoefficient does what you want:
In[3]:= SeriesCoefficient[x*Exp[t*x], {x, 0, m}]
Out[3]= Piecewise[{{t^(-1 + m)/(-1 + m)!, m >= 1}}, 0]
The final output is the general form of the m'th derivative. The PieceWise is not really necessary, since the expression actually holds for all non-negative integers.
Thanks to your update, it's clear what's happening here. Mathematica doesn't actually calculate the derivative; you then replace x with 0, and it ends up looking at this:
D[Exp[t*0],{0,m}]
which obviously is going to run into problems, since 0 isn't a variable.
I'll assume that you want the mth partial derivative of that function w.r.t. x. The t variable suggests that it might be a second independent variable.
It's easy enough to do without Mathematica: D[Exp[t*x], {x, m}] = t^m Exp[t*x]
And if you evaluate the limit as x approaches zero, you get t^m, since lim(Exp[t*x]) = 1. Right?
Update: Let's try it for x*exp(t*x)
the mth partial derivative w.r.t. x is easily had from Wolfram Alpha:
t^(m-1)*exp(t*x)(t*x + m)
So if x = 0 you get m*t^(m-1).
Q.E.D.
Let's see what is happening with a little more detail:
When you write:
D[Sin[x], {x, 1}]
you get an expression in with x in it
Cos[x]
That is because the x in the {x,1} part matches the x in the Sin[x] part, and so Mma understands that you want to make the derivative for that symbol.
But this x, does NOT act as a Block variable for that statement, isolating its meaning from any other x you have in your program, so it enables the chain rule. For example:
In[85]:= z=x^2;
D[Sin[z],{x,1}]
Out[86]= 2 x Cos[x^2]
See? That's perfect! But there is a price.
The price is that the symbols inside the derivative get evaluated as the derivative is taken, and that is spoiling your code.
Of course there are a lot of tricks to get around this. Some have already been mentioned. From my point of view, one clear way to undertand what is happening is:
f[x_] := x*Exp[t*x];
g[y_, m_] := D[f[x], {x, m}] /. x -> y;
{g[p, 2], g[0, 1]}
Out:
{2 E^(p t) t + E^(p t) p t^2, 1}
HTH!

How do I make this substitution in Mathematica?

I'm just getting started with Mathematica, and I've got what must be a pretty basic question about making substitutions but I can't get it to work.
I'd like to find the Euler-Lagrange equations for a functional of the function phi[x,y] and then make a substitution for the function phi[x,y]
If I enter the following:
VariationalD[tau*phi[x, y]^2 - 2*phi[x, y]^4 + phi[x, y]^6 + Dot[D[phi[x, y], {{x, y}}], D[phi[x, y, {{x, y}}]]], phi[x, y], {x, y}]
I get
Plus[Times[2,tau,phi[x,y]],Times[-8,Power[phi[x,y],3]],Times[6,Power[phi[x,y],5]],Times[-2,Plus[Derivative[0,2][phi][x,y],Derivative[2,0][phi][x,y]]]]
Now if I try % /. phi[x,y] -> phi0[x,y] + psi[x,y] it makes the substitution for all the polynomial terms, but not for the Derivative terms.
How do I force the substitution into those functions?
I agree with all of what rcollyer says, but I think his final solution might be a little opaque.
The simplest rule that I could come up with (which is the basically the same as rcollyer's) is
{phi[x__] :> phi0[x] + psi[x], f_[phi][x__] :> f[phi0][x] + f[psi][x]}
or something with less possible side effects is
{phi[x__] :> phi0[x] + psi[x], Derivative[n__][phi][x__] :> Derivative[n][phi0][x] + Derivative[n][psi][x]}
It would be a lot easier if Derivative had a Default property (compare Default[Times] with Default[Derivative]). It should be something like Default[Derivative] := Sequence[] but unfortunately that doesn't play nice with the pattern matching.
Getting back to your question, you probably want to define something like
VariationalD[expr_, sym_, var_] := Module[{
vRule = {sym[x__] :> sym[x] + var[x],
Derivative[n__][sym][x__] :> Derivative[n][sym][x] + Derivative[n][var][x]}},
(expr /. vRule) - expr]
Where the variation var of the symbol sym is assumed to be small. Of course what you then need to do is series expand around var=0 and only keep the linear part. Then use integration by parts on any term which has derivatives of var. All of which should be included in the above module.
First, you misplaced a ] in your second derivative term, it should read D[phi[x, y], {{x, y}}]] not D[phi[x, y, {{x, y}}]]].
That said, replacement in Mathematica can be tricky, as has been pointed out in other questions. That isn't to say it is impossible, just requires some work. In this case, the problem comes in in that phi[x,y] is different from Derivative[2, 0][phi][x, y]. So, your pattern won't match the derivative term. The simplest thing to do is to add the rule
Derivative[a__][phi][x__]:> Derivative[a][phi0][x] + Derivative[a][psi][x]
to your list of replacement rules. Three things to note: 1) I use ReplaceDelayed so that both types of derivatives will match without writing multiple rules, 2) since I can use patterns, I named them so that I can refer to them on the RHS of the rule, and 3) I used a double underscore when defining a and x which will match one or more items in a sequence.
Of course, that isn't the most satisfying way to approach the problem, as it will require you to write two rules every time you wish to this sort of replacement. It turns out a more general approach is surprisingly difficult to accomplish, and I'll have to get back to you on it.
Edit: This requires a double replacement, as follows
<result> /. phi -> phi0 + psi /. a_[b__][c__] :> Through[Distribute[a[b]][c]]
Distribute ensures that the derivative works correctly with Plus, and Through does the same with the function args c. The key is that the Head of Derivative[2, 0][phi][x, y] is Derivative[2, 0][phi], hence the several levels of square brackets in the rule.

Resources