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}}}

0 Comments:

Post a Comment

<< Home