Mathematica programming

Wednesday, July 26, 2006

Brackets for zeros of just plotted function

Given a complicated function one often waits significant amount of time for the function to plot. Once plotted you might want to determine its zeros, or other constant values saving oneself a call to
FindRoot
. The following function extract zero brackets from the given plot:
AllZeroInThePlot[gr_Graphics, val_:0] :=
Catch[Module[{a, pos, x, k},
a = First[gr]; pos = Position[a, Line[_List]];
If[pos==={}, Throw[$Failed]];
a = Extract[a, pos]; k = 0;
k = (Reap[Scan[Function[ln,
x = ln /. Line -> Identity;
x = Split[x, Sign[Last[#1]-val] == Sign[Last[#2]-val] &];
If[Length[x] > 1,
x = ((Sequence @@ Through[{First, Last}[#]]) & /@ x);
x = Flatten[First /@ x];
x = Prepend[x, First[x]];
x = Append[x, Last[x]];
x = Rest[Most[Partition[x, 2]]];
Sow[x, k]; k++;];],a]]//Last);
(Flatten[#, 1] & /@ k) /. {x1_, x2_} /; x1 == x2 :> {x1}
]]
Then
In[64]:=
gr=Plot[{AiryAi[-x],AiryBi[-x]},{x,0,5}];

In[65]:=
zeros =AllZeroInThePlot[gr]

Out[65]=
{ { {2.28795,2.50089}, {3.98017,4.19035}},
{ {1.04426,1.24898}, {3.12924,3.33915}, {4.79223,5.}}
}
Or, use it to find where function attains a particular value:
In[67]:=
gr2=Plot[Sin[x]/x,{x,0,5}];

In[68]:=
AllZeroInThePlot[gr2,0.5]

Out[68]=
{{{1.88289,2.09816}}}

Tuesday, July 25, 2006

ExcudedForms for Simplify


We shall define
Simplify2[e_, opts__]
admitting an option
ExcludedForms
, just like
FullSimplify
does.
The idea behind, is to wrap parts matching excluded patterns around with
Hold
, do the simplification and restore held parts back to normal.

In[38]:=
Options[Simplify2] =
Union[Options[Simplify], {ExcludedForms :> {}}];

In[39]:=
Simplify2[e_, (opts___)?OptionQ] :=
Catch[Module[{popts, tag, ef, p},
popts = FilterOptions[Simplify, opts];
ef = ExcludedForms/.{opts}/.Options[Simplify2];
If[ef === {}, Throw[Simplify[e, popts]]];
ef = Alternatives @@ ef;
Simplify[
e /. RuleDelayed @@ {p:ef, Hold[tag[p]]}
, popts] /. {Hold[tag[p_]] :> p}
]]

In[40]:=
Simplify2[Sin[x]^4 + Cos[x]^4 + Sin[x]^2 + Cos[x]^2]

Out[40]=
(1/4)*(7 + Cos[4*x])

In[41]:=
Simplify2[Sin[x]^4 + Cos[x]^4 + Sin[x]^2 + Cos[x]^2,
ExcludedForms -> {(_Sin | _Cos)^4}]

Out[41]=
1 + Cos[x]^4 + Sin[x]^4
Enjoy!