# Fitting a Function With a Numerical Integral [duplicate]

This question already has an answer here:

I am having trouble using FindFit with the following function.

f[x_] := NIntegrate[a x k, {k, 0, 1}];

data = {{0, 0}, {0.2, 0.1}, {0.4, 0.2}};

param = FindFit[data, {f[x],2>a>1},a, x]


I get the following error

NIntegrate::inumr: The integrand a k x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>


Yet I can easily plot the function if I set "a" to any value between 1 and 2. So I assume FindFit is not assigning "a" a numerical value for some reason?

This function is the simplest function in which I can reproduce the error (The data set is similarly a toy dataset). The actual function I need to use will be more complicated, so unfortunately getting rid of NIntegrate is not possible.

Thanks

-

## marked as duplicate by Michael E2, R. M.♦Nov 28 '13 at 0:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

See What are the most common pitfalls awaiting new users? on the use of NumericQ. – Michael E2 Nov 27 '13 at 22:45

## 1 Answer

This is the approach I usually use in this situation:

f[(a_)?NumericQ, (x_)?NumericQ] := NIntegrate[a*x*k, {k, 0, 1}];
data = {{0, 0}, {0.2, 0.1}, {0.4, 0.2}};
param = FindFit[data, {f[a, x], 2 > a > 1}, a, x]


The ?NumericQ predicate will prevent evaluation of f until it gets numerical values, since NIntegrate cannot work with symbolic integrands. In this particular circumstance, however, a new set of errors is generated

NIntegrate::izero: Integral and error estimates are 0 on all integration subregions.
Try increasing the value of the MinRecursion option. If value of integral may be 0,
specify a finite value for the AccuracyGoal option.


I will leave that one for someone else to solve.

-
Thanks, this worked for my more complicated function. – ThomasKelly Nov 28 '13 at 15:02