...

View Full Version : Cosine fitting function



Jiff
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!

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

jkd
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:
y=A*cos(omega*t+phi)
http://www.tlhiv.org/cgi-bin/LaTeXpreviewer/preview.cgi?hash=5990eb75fd389c63c92078bbcb5caf7d

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)
http://www.tlhiv.org/cgi-bin/LaTeXpreviewer/preview.cgi?hash=98f1e218f4768dd8e198229f6bf5aced

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.

jkd
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.

jkd
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).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum