# How to have NonlinearModelFit not evaluate a function too early?

This is a follow up of my previous question How can I define the following function for arbitray values of the arguments? that received no attention so here I will try to be more concise with the problem without drowning in details.

So here we go. What I wanna do is a fit. I have a function that has two arguments fun[x, l]. x will be the x axis of the fit, so to speak and l is the parameter I want to fit.

To this end I use

NonlinearModelFit[data, fun[x, l] , {l}, x, Weights -> 1/dataError^2];
%["BestFitParameters"]
%%["EstimatedVariance"]


The function fun uses another function NNfun[x, l] where the first argument will be used as the x axis in NonlinearModelFit and I again have l the parameter I want to fit.

I ran into some nonsensical things while trying the fit above and eventually I realized what the issue was. The issue is that NNfun[x, l] does what it is supposed to do when I feed it actual values of x or l but when I evaluate say NNfun[0.1, l] it always returns -1 (the details of why -1 are given in my previous question I mention above).

Thus when I fed fun[x, l] to NonlinearModelFit I was feeding the wrong function because NNfun[x, l] always evaluated to -1, which is not correct. That is, the problem is that this function only works for actual values of its arguments, but if l is left arbitrary, which is what I need to perform the fit, it doesn't.

I have tried to define NNfun[x, l] alternatively but so far I have not come to anything that works. So I wonder if there is a way to feed NNfun[x, l] somehow "freezing" the evaluation so that NonlinearModelFit fits the function I want to fit. Can I somehow achieve this?

• So, in order to understand why the function returns -1 one needs to read another lengthy post? – yarchik Oct 17 at 9:56
• @yarchik yeah, I mean, the point of this post is to condense the other one. because it received no attention. The reason in a nutshell is that I use a while loop in NNfun where I initialize a variable and if I do not give actual values of the parameter s to NNfun the while loop doesnt do anything useful and the output value is the initialized value which is -1. – PhoenixPerson Oct 17 at 10:00

## 1 Answer

You should define your objective function using the "black box" pattern in order to prevent symbolic processing by NonlinearModelFit:

fun[r_?NumericQ, l_?NumericQ] :=Sum[a[1/r, l]^n, {n, 1, NNfun[r,l]+1}]


Actually such questions were asked already many times on this site, see this FAQ answer:

This pattern also mentioned in the official Documentation in some places:

A Wolfram Quick Answers artice: