How to calculate an integral of an expression that is determined numerically (in Mathematica)?

First of all, I am fairly new to Mathematica and Stackoverflow, so please feel free to give me any advice whatsoever.

I aim to calculate an integral of an expression that has been determined numerically. I will give a simple example:
A solution (dependent on some parameter value a) is derived by

Sol[a_] := FindInstance[x^2 == a, x]

and results are fine:



{{x -> 2}}.

Obviously, this special example could be solved algebraically, but since the set of equalities and inequalities I want to analyse is much more complicated, FindInstance (and therefore numerical evaluation) is the only option I could think of (the results from Reduce are to complicated to be checked by hand and I don’t know how to elegantly get results from Reduce in an automated way; if you have recommendations on how to approach the results from Reduce, please let me know).

I now aim to calculate the integral of the solution given above and try

In[3]:= NIntegrate[(x /. Sol[a][[1]]), {a, 1, 4}]

During evaluation of In[3]:= FindInstance::exvar: The system contains a nonconstant expression a independent of variables {x}.

During evaluation of In[3]:= ReplaceAll::reps: {x^2==a} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.

During evaluation of In[3]:= NIntegrate::inumr: The integrand x/.x^2==a has evaluated to non-numerical values for all sampling points in the region with boundaries {{1,4}}.

Out[3]= NIntegrate[x /.Sol[a][[1]], {a, 1, 4}]

To mee, it seems like NIntegrate does not “take a value of a and plug it into Sol, calculate Sol[a] and proceed to the next value of a”. Therefore I tried to force Mathematica to evaluate Sol with numerical values for a using commands like Evaluate, With, Block, Module but was unsuccesful (which might be due to poor understanding of these commands).

Thanks for reading and maybe helping me out!



1 Answer


In general you can define

Sol[a_?NumericQ] := FindInstance[x^2 == a, x][[1, 1, 2]]


(* 4 *)

NIntegrate[Sol[a], {a, 1, 4}]
(* 4.66667 *)



Works like a charm, thanks!
– Mitch D
Feb 1 ’13 at 23:37