2
$\begingroup$

I have a problem where I am using FindRoot a gazillion times over a grid of parameters. I need to allow the starting values to vary a bit with the parameters to get it to converge. Here is a simple example in the spirit of my much bigger problem:

f[a_] := x /. FindRoot[x^2 - 1 == a, {x, a - 1, a + 1}]
NIntegrate[f[z], {z, 0, 5}]

NIntegrate actually gives an answer (I think it's even right), but it also gives the following errors:

FindRoot::srect: Value -1.+z in search specification {x,z-1,z+1} is not a number or array of numbers. >>

ReplaceAll::reps: {FindRoot[x^2-1==z,{x,z-1,z+1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

It looks like it doesn't like treating the starting values for x as variables. For some reason, the actual numbers between 0 and 5 in the integral are not being passed to the starting values in FindRoot. Any suggestions?

$\endgroup$

1 Answer 1

6
$\begingroup$

Not sure about what you're trying to do, but this doesn't bring up errors:

ClearAll[f];
f[a_?NumericQ] := x /. FindRoot[x^2 - 1 == a, {x, a - 1, a + 1}]
NIntegrate[f[z], {z, 0, 5}]

(*
-> 9.13129
*)

Edit

The result is (of course) equivalent to

Integrate[Sqrt[1 + z], {z, 0, 5}]

(*
-> -(2/3) + 4 Sqrt[6]
*)
$\endgroup$
3
  • $\begingroup$ Thanks for the suggestion. I don't know the syntax a_?NumericQ, so I'm showing my limited knowledge of the program, but I'll look it up and give it a try. My problem involves integrating over functions of the normal PDF, which has no closed form, so I definitely need the numerical routine. $\endgroup$
    – Dan
    May 6, 2013 at 0:35
  • $\begingroup$ belisarius, This worked. I've got a few hundred thousand solutions to FindRoot with starting values that a funciton of a subset of the parameters. This ensures that they are in regions that generate solutions. Then I've got a few hundred thousand numerical integrals of functions with the FindRoot solutions embeded, all solving nicely. Thanks. $\endgroup$
    – Dan
    May 6, 2013 at 17:06
  • $\begingroup$ @Dan Glad to hear that $\endgroup$ May 6, 2013 at 17:09

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .