View Full Version : Cosine fitting function

08-21-2007, 10:16 PM
I am looking for an algorithm that will take data points and fit a cosine function to them. Anyone know of an algorithm that can fit data to a cosine function in general? :confused: The algorithm can be in any language (hence the general) but ultimately I will need it in C. Thanks for your help!

08-23-2007, 11:28 PM
Any help?:confused:

08-24-2007, 06:59 AM
Do you know anything about the distribution that the data points are sampled from? Without that, you would have to do a least-squares regression...

Ultimately, any sinusoidal curve should be represented as:

Thus, you take 3 partial derivatives of the least squares value and set equal to zero. I did this out
I just did out some of the calculus, and the 3 resulting equations cannot be analytically solved for (A,omega,phi)

You could run a solver for the 3 variables and get approximations. Alternatively, you could try doing the following:

1. Guess an amplitude. Divide all your data points by it, then take the inverse cosine of these new values. Run a linear regression on this new data set to get omega and phi.
2. Adjust amplitude, repeat (1), and compare errors. The L_2 error is a continuous function of A, so you should be able to find a local minimum without too much work.

You could even creatively guess at A... perhaps the average of the two most extreme values, or the average of all the values. Those are the two best possibilities that come to mind.

08-24-2007, 07:02 AM
Incidentally, depending on how tightly grouped on the scale you are examining the values you are sampling are, you might be able to replace the cosine function with the first few terms of its Taylor expansion; the polynomial approximation should be much easier to regress on.

08-24-2007, 07:33 AM
And oops, this was assuming that the sinusoidal curve's offset is 0 along the y-axis (which is not necessarily accurate at all; if that isn't the case, you need to add another parameter to the least-squares analysis).