0

I have an equation which is itself a numerical integral function of a parameter, as follows:

f[a_?NumericQ] := NIntegrate[a*x^2, {x, 0, 1}]
NSolve[f[a] == 2, a,Reals]

However I am not able to arrive at any output.

Is there any way to solve the problem?

Utsab Dey
  • 53
  • 5

3 Answers3

1

Try NMinimize

NMinimize[{1, f[a] == 2}, a ]
(*{1., {a -> 6.}}*)

This (see comment @b.gates.you.know.what)

FindRoot[f[a] == 2, {a, 1 }]

also works.

Ulrich Neumann
  • 53,729
  • 2
  • 23
  • 55
1
Clear["Global`*"]

f[a_?NumericQ] := NIntegrate[a*x^2, {x, 0, 1}]

When FindRoot fails, it is often due to using a poor initial estimate. To get better starting values, plot a rough inverse of f[a] in the region of interest.

ListLinePlot[{#, f[#]} & /@ Range[1, 11, 5],
 PlotMarkers -> Automatic]

enter image description here

Use a rough estimate of the inverse as the starting value in FindRoot

arg[fv_] := a /. FindRoot[f[a] == fv, {a, 3/10 fv}]

arg[2] // AbsoluteTiming

(* {0.030148, 6.} *)

The result is the same as that from NMinimize

NArgMin[(f[a] - 2)^2, a] // AbsoluteTiming

(* {2.57372, 6.} *)

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
1

Numerical methods for root-finding generally have limitations, outside of which they fail. Take your pick:

  • NSolve: Finds (all) numerical solutions to (constrained) symbolic equations. Best on polynomial problems (especially univariate), excellent on univariate analytic function on compact domains (closed bounded intervals), less robust on multivariate problems as the dimension increases. Never works on the OP's type of problem. Will find the first root of an InterpolatingFunction and other functions on which InverseFunction operates successfully. Otherwise, NSolve does not work on function defined by numerical processes.
  • FindRoot: Finds a single root. Usually succeeds, sometimes fails on the OP's type of problem. Compare with NSolve never working.
  • NMinimize or FindMinimum on the square of the residual, or as @Bob and @Ulrich have done. Both find a single solution only. Sometimes fails. Examples here: FindMinimum or NMinimize.
  • Plot based solver for real univariate problems: Jen's findAllRoots: Find all roots of an interpolating function (solution to a differential equation) Finds all roots in an interval. Sometimes fails.
  • Package for real univariate problems: Ted Ersek's RootSearch.
  • NDSolve based root search: here or here.

Tolstoy's dictum, "Unhappy codes are unhappy in their own way," means users have to think about their problem and adjust accordingly. And share realistic minimal working examples, if they want help.

(Defining f thus, f[a_] = a*NIntegrate[x^2, {x, 0, 1}], removes all numerical difficulties and even opens the problem to symbolic methods. It's obviously a toy example, and the OP states in a comment that some actual use-cases do not work with FindRoot, in whatever way the OP applied FindRoot.)

Michael E2
  • 235,386
  • 17
  • 334
  • 747