# How to fit one function into the form of another?

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!

• 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. – Hugh Apr 30 '19 at 15:58
• Numerical values will do! Thanks. – Houndbobsaw Apr 30 '19 at 16:02
• 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. – Hugh Apr 30 '19 at 16:06
• Thank you! I think I Roman's answer suffices. – 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π/Ω}]

If your function g[t] is simple enough, you can even replace the numerical integrals by analytic ones (NIntegrate becomes Integrate).
• 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. – Roman Apr 30 '19 at 16:32
• @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.) – Michael E2 Apr 30 '19 at 16:47