MathGroup Archive 1990

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Fitting data with Mathematica


> If I want to fit data to an expression which I already know the
> functional form of, but which contains adjustable parameters such as
> the value of a magnetic field, initial angle of a nuclear spin with
> respect to that field, etc., how do I use Mathematica to find
> least-squares "best" values of these parameters to fit the data? In
> other words, how do I use Mathematica to obtain non-linear,
> parametric, least-squares fits to experimental data?

The trick is to use FindMinimum.  Develop your own function that 
expresses the goodness of fit.  The sum of squares of differences is
probably the thing to use.  Then use FindMinimum.  Here is an example

I made a list of points in "datalist" that were pairs {x,3.456
E^(2.345 x)} for 300 random values of x.  Now suppose we only knew
that the form of the functions was f[x] = a + E^(b x) and we want to
find a and b.  "fitfunction" tells how good a given a and b fit the
data.  In step 11 I invoke FindMinimum telling it to start looking
around a=3 and b=2.  

In[10]:= fitfunction[a_,b_] := Apply[Plus,Map[(#[[2]]-(a E^(b #[[1]])))^2&,

In[11]:= FindMinimum[fitfunction[a,b],{a,3},{b,2}]

Out[11]= {0., {a -> 3.456, b -> 2.345}}

The one catch is that I think FindMinimum will barf if it can't
differentiate to get gradient functions.  I haven't tried something
that will test this, though.

There are options to FindMinimum.  Read its description carefully.  Be
careful of the WorkingPrecision option.  It can be dangerous.  

  -- David Jacobson

  • Next by Date: Spherical Harmonic summary
  • Next by thread: Spherical Harmonic summary