Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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}]
share|improve this question
@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
up vote 6 down vote accepted

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

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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