# Fitting a sine function to data

I have a sequence of $n$ points $(x_i,y_i)$, for $i=1,\dots,n$. I would like to find the function, of the form $y=V\sin(x+\phi)$, which best fits the points. Which numerical method could I use? I have a slow system, with little memory, so I am searching for a fast and efficent method, even if not very accurate.

I have tried with gradient descent, but it is slow.

-
How do you define "best fit"? –  Listing Nov 25 '11 at 23:14
The usual method for least-squares fitting is Levenberg-Marquardt. Of course, this needs a good initial estimate for your model's parameters, as with most iterative methods. –  Guess who it is. Nov 26 '11 at 2:02
You can look at things like Prony's Method, Espirit and music. –  Batman Apr 3 at 21:02

Here is a very simple-minded way.

First, set $V = \max(|y_i|)$.

Then, let $\phi_i =\arcsin(y_i/V)-x_i$.

Finally, $\phi =\frac1{n}\sum \phi_i$.

Note: If the data is over multiple sinusodial cycles, adjust $\phi_{i+1}$ so it differs from $\phi_i$ by less than $\pi$.

-
And from here, nonlinear regression must start. –  Claude Leibovici Apr 4 at 6:03

For illustration purposes of Marty Cohen's answer, I generated $50$ data points ($i$ from $1$ to $50$), $x_i=i$, $y_i=12.34 \sin (x_i+2.345)+2(-1)^i$ (the error is quite large).

The largest absolute value of the $y_i$'s is $14.3129$. From there, the sum of the $\phi_i$'s equals $-1275.08$ so $\phi =-25.5017$; adding $9\pi$, this gives $\phi=2.7726$.

Using these estimates, I started a nonlinear regression which converged immediately and the final result is $$y=12.3509 \sin (x+2.3454)$$

If you are in big trouble, may be because of large errors, what you could do is the following : consider $\phi$ as fixed and so, $$V(\phi)=\frac{\sum _{i=1}^n y_i \sin (x_i+\phi )}{\sum _{i=1}^n \sin ^2(x_i+\phi )}$$ and now consider $$SSQ(\phi)=\sum_{i=1}^n\Big(V(\phi)\sin(x_i+\phi)-y_i\Big)^2$$ Plot $SSQ(\phi)$ as a function of $\phi$, try to locate a minimum. Now, you have all the elements for starting the nonlinear regression for the two parameters.

-