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}]
  • $\begingroup$ @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? $\endgroup$ – coderdave Nov 30 '13 at 17:40
  • $\begingroup$ 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. $\endgroup$ – Oleksandr R. Nov 30 '13 at 17:43
  • $\begingroup$ @OleksandrR. Thank you! $\endgroup$ – coderdave Nov 30 '13 at 18:02

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]

enter image description here

  • $\begingroup$ Oh cool thanks! I like the plot style as well - helps visualize the error. $\endgroup$ – coderdave Nov 30 '13 at 17:42
  • $\begingroup$ 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! $\endgroup$ – coderdave Nov 30 '13 at 19:09
  • $\begingroup$ @coderdave It works without Evaluate. Take a look here to see why I used it. $\endgroup$ – Szabolcs Nov 30 '13 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.