# Fitting one function to another

I'd like to see how close I can fit an exponential function to a cosine function in the domain of $\;-\frac{\pi}{2}$ to $\frac{\pi}{2}$ in the least squares sense.

FindFit[Cos[x], {A*Exp[l*(Cos[x] - 1)], -π/2 <= x <= π/2}, {A, l},  x]

FindFit::fitd: First argument Cos[x] in FindFit is not a list or a rectangular array.


I could create a table for Cos[x] to pass as the first parameter but I feel like I'm approaching this wrong and should be able to give Mathematica my problem in symbolic form. Perhaps, I should try Minimize but I didn't get any results out of it.

Minimize[{(Cos[x] - A*Exp[l*(Cos[x] - 1)])^2, -π/2 <= x <= π/2}, {A, l, x}]

Minimize[{(-A E^(l (-1 + Cos[x])) + Cos[x])^2, -π/2 <= x <= π/2}, {A, l, x}]

• @OleksandrR. Oh, right silly mistake, of course I need to minimize the sum of the squares. Just curious why can't it find an exact closed form solution? – coderdave Nov 30 '13 at 17:40
• Have a look at the solution to the integral. It contains Bessel and Struve functions. That one cannot find exact closed form arguments for these functions to make the integral equal a particular value is not too surprising, IMO. – Oleksandr R. Nov 30 '13 at 17:43
• @OleksandrR. Thank you! – coderdave Nov 30 '13 at 18:02

## 1 Answer

You can do the integral symbolically, then minimize numerically:

distance =
Integrate[(A*Exp[l*(Cos[x] - 1)] - Cos[x])^2, {x, -Pi/2, Pi/2},
Assumptions -> (A | l) \[Element] Reals]

{min, sol} = NMinimize[distance, {A, l}]

Plot[{A*Exp[l*(Cos[x] - 1)], Cos[x]} /. sol // Evaluate, {x, -Pi/2, Pi/2},
Filling -> {1 -> {2}}, PlotStyle -> Black] • Oh cool thanks! I like the plot style as well - helps visualize the error. – coderdave Nov 30 '13 at 17:42
• I'm trying to understand the plot. You first do a replace via the symbol /. that replaces A and l with the sol variable. Then what does the // Evaluate do? Thanks! – coderdave Nov 30 '13 at 19:09
• @coderdave It works without Evaluate. Take a look here to see why I used it. – Szabolcs Nov 30 '13 at 22:52