I have a slightly complicated periodic function of one variable t, say g[t].

I want to do a least squares fit of that function into the form A*Cos[Ω*t]+B*Cos[2Ω*t], and figure out the values of parameters A and B.

Is there a way to do this in Mathematica? Thanks in advance!

  • $\begingroup$ Do you want numerical values for A and B or symbolic values? Numerical is very straightforward. Symbolic may end up with very large expressions. It would be nice if we had some code from you so that we could play with it. $\endgroup$ – Hugh Apr 30 '19 at 15:58
  • $\begingroup$ Numerical values will do! Thanks. $\endgroup$ – Houndbobsaw Apr 30 '19 at 16:02
  • 2
    $\begingroup$ This post shows how to use Fourier to calculate a spectrum of values for A and B. Do you really just want the first and second harmonic? Roman's answer below will work fine for calculating individual values. An example from you would clarify what you want. If you can, please edit your post and add an example. $\endgroup$ – Hugh Apr 30 '19 at 16:06
  • $\begingroup$ Thank you! I think I Roman's answer suffices. $\endgroup$ – Houndbobsaw Apr 30 '19 at 20:41

These are regular orthogonal-function integrals: assuming that the period of your function g[t] is T=2π/Ω, you can compute

A = Ω/π*NIntegrate[g[t]*Cos[Ω*t], {t, 0, 2π/Ω}]
B = Ω/π*NIntegrate[g[t]*Cos[2Ω*t], {t, 0, 2π/Ω}]

If your function g[t] is simple enough, you can even replace the numerical integrals by analytic ones (NIntegrate becomes Integrate).

  • $\begingroup$ hi, thanks for your answer! I will try this later, but just to clarify, will NIntegrate work to approximate any function? g(t) is very ugly and Integrate itself cannot solve it. $\endgroup$ – Houndbobsaw Apr 30 '19 at 15:52
  • $\begingroup$ As long as the numerical integrals converge, you're safe and get an optimal fit in the least-squares sense. If NIntegrate struggles too much, it will throw messages, and in that case you can come back here to ask another question about "How do I make this numerical integral converge?" and using options/tricks/methods. $\endgroup$ – Roman Apr 30 '19 at 16:32
  • $\begingroup$ @Houndbobsaw I would recommend the method option Method -> "Trapezoidal" for NIntegrate in this case, unless g[t] has singularities. The smoother g[t] is, the faster the convergence, in general. The main issues of numerical integration -- speed of evaluation of the integrand, singularities, oscillatory behavior -- are quite distinct from the issues in symbolic integration. (Hugh's Fourier method will also approximate A and B.) $\endgroup$ – Michael E2 Apr 30 '19 at 16:47

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.