Skip to main content

equation solving - How to find numerically all roots of a function in a given range?



It is common that I search numerically for all zeros (roots) of a function in a given range. I have written two simple minded functions that perform this task, and I know of similar functions on this site (e.g. this, this, and this).


I think this community will benefit if we could compile a list of functions that do so, with some explanations about efficiency considerations, in what context should we use which approach, etc.



The problem definition: given a function f and a range {x1,x2}, write a function that finds all (or most) roots of f in the given range.




Answer



First, it might be worth pointing out that in recent versions of Mathematica, Solve and NSolve are quite strong at solving equations with standard special functions.


With[{f = BesselJ[1, #^(3/2)] Sin[#] &},
solvesol = x /. Solve[{f[x] == 0, 25 <= x <= 35}, x];
Plot[f[x], {x, 25, 35},

MeshFunctions -> {# &}, Mesh -> {solvesol},
MeshStyle -> Directive[PointSize[Medium], Red]
]
]


Solve::nint: Warning: Solve used numeric integration to show that the solution set found is complete. >>



Mathematica graphics





For other functions, provided they are continuous and not too oscillatory, then in addition to ODE approach in yohbs's NDSolve solution, we can solve the system with a DAE that does not need the function to be differentiable.


ClearAll[NrootSearch2];

Options[NrootSearch2] = Options[NDSolve];
NrootSearch2[f_, x1_, x2_, opts : OptionsPattern[]] :=
Module[{x, y, t, s},
Reap[
NDSolve[{x'[t] == 1, x[x1] == x1, y[t] == f[t],
WhenEvent[y[t] == 0, Sow[s /. FindRoot[f[s], {s, t}],
"zero"],

"LocationMethod" -> "LinearInterpolation"]},
{}, {t, x1, x2}, opts],
"zero"][[2, 1]]];

With[{f = BesselJ[1, #^(3/2)] Sin[#] &},
nrootsol = NrootSearch2[f, 25, 35];
Plot[f[x], {x, 25, 35},
MeshFunctions -> {# &}, Mesh -> {nrootsol},
MeshStyle -> Directive[PointSize[Medium], Red]
]

]



For functions like the example we've been using, we can combine the previous method with Root to produce exact results. (Caveat: Managing the precision of the approximate root is not always straightforward. Adjusting the WorkingPrecision option to FindRoot might be necessary. The code below tries it first at $MachinePrecision, and if that fails, then it tries a WorkingPrecision of 40.)


ClearAll[rootSearch2];

Options[rootSearch2] = Options[NDSolve];
rootSearch2[f_, x1_, x2_, opts : OptionsPattern[]] :=
Module[{x, y, t, s, res, tmp},
Reap[

NDSolve[{x'[t] == 1, x[x1] == x1, y[t] == f[t],
WhenEvent[y[t] == 0,
Sow[Quiet[
res = Check[
Root[{f[#] &,
s /. FindRoot[f[s], {s, t}, WorkingPrecision -> $MachinePrecision]}],
$Failed]];
If[res === $Failed, (* if $MachinePrecision fails, try a higher one *)
Quiet[
res = Check[

Root[{f[#] &,
tmp = s /.
FindRoot[f[s], {s, t}, WorkingPrecision -> 40]}],
res = tmp]]]; (* if both fail, return approximate root *)
res,
"zero"],
"LocationMethod" -> "LinearInterpolation"]},
{}, {t, x1, x2}, opts],
"zero"][[2, 1]]];


Note it returns 8 π etc. for the roots of the sine factor:


With[{f = BesselJ[1, #^(3/2)] Sin[#] &},
exactsol = rootSearch2[f, 25, 35]
]
(*
{8 π,
Root[{BesselJ[1, #1^(3/2)] Sin[#1] &,
25.192448602298225837336093255176323600186894730 + 0.*10^-46 I}],
Root[{BesselJ[1, #1^(3/2)] Sin[#1] &, 25.60802500579825}],
...,

11 π,
Root[{BesselJ[1, #1^(3/2)] Sin[#1] &, 34.76570243333289}]}
*)



Comparisons:


The two exact methods:


SortBy[N]@solvesol - exactsol // N[#, $MachinePrecision] &



N::meprec: Internal precision limit $MaxExtraPrecision = 50.` reached while evaluating {0,<<28>>,0}. >>



(*
{0, 0.*10^-65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
*)

The two root-search methods:


nrootsol - N@exactsol
Max@Abs[%]

(*
{0., 4.79616*10^-13, 3.55271*10^-15, 0., 0., 0., 0., 0., 0., -1.84741*10^-13,
2.8777*10^-13, 0., 0., 0., 0., 0., -3.55271*10^-15, 0., 0., 3.01981*10^-13, 0., 0., 0.,
0., 0., 0., 7.10543*10^-15, -5.96856*10^-13, 7.10543*10^-15, 0.}

5.96856*10^-13
*)

Comments

Popular posts from this blog

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...

calculus and analysis - Integral of the Sinc product

Let us consider the following integral $$ B_n = \int_0^\infty \prod_{k=1,3,5,\dots}^n\frac{\sin (x/k)}{x/k}dx $$ By definition, Sinc[x] == Sin[x]/x , therefore B[n_?OddQ] := Integrate[Product[Sinc[x/k], {k, 1, n, 2}], {x, 0, Infinity}] B /@ Range[1, 13, 2] {Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2} OK, everything is fine. But... B[15] 467807924713440738696537864469 Pi/935615849440640907310521750000 What's going on? Answer As Eckhard wrote in comments B[n] is the n-th Borwein integral . (The letter B was not accidental :) ) This funny properties of Borwein integrals is related to the Fourier transform of Sinc function FourierTransform[Sinc[x], x, k] 1/2 Sqrt[Pi/2] (Sign[1 - k] + Sign[1 + k]) Plot[%, {k, -2, 2}, Filling -> 0] which is the box function. The result is $\pi/2$ while the sum $$ 1/3+1/5+\dots+1/n $$ B_n = \frac{\pi}{2} - \pi \bigg(\sum_{k=3,5,\ldots}^n\frac{1}{k} -1\biggr)^\frac{n-1}{2}\prod_{k=3,5,\dots}^n\frac{k}{k-1}. $$ For $n=15$ it is equal to $$ \frac{46780...

list manipulation - Selecting multiple columns from a matrix?

Sample data: data = { {{2013, 1, 1}, 24.13, 167.67, 231.82}, {{2013, 1, 2}, 32.15, 170.92, 225.99}, {{2013, 1, 3}, 35.43, 172.68, 221.67}, {{2013, 1, 4}, 36.73, 173.05, 218.32}, {{2013, 1, 5}, 58.19, 165.96, 197.05}, {{2013, 1, 6}, 69.99, 163.50, 187.52}, {{2013, 1, 7}, 71.37, 154.21, 175.58}, {{2013, 1, 8}, 72.51, 149.66, 163.25}}; I want a DateListPlot with three graphs, so for a matrix formed by columns 1 and 2, one for columns 1 and 3, and 1 for columns 1 and 4. At the moment I'm using this code: data2 = Transpose[{data[[All, 1]], data[[All, 2]]}]; data3 = Transpose[{data[[All, 1]], data[[All, 3]]}]; data4 = Transpose[{data[[All, 1]], data[[All, 4]]}]; DateListPlot[{data2, data3, data4}, Joined -> True, Filling -> {3 -> {1}}] but I have a hunch that this can be done more efficiently. I don't like the Transpose s in particular. Any ideas? edit (for extra credit) What if I need to multiply the second column by 2, which in my solution is simp...