Curve fitting to a*cos^2(b+x)

I would like to fit A*cos^2(B+x)=y function to a few points (I’m searching for the values of A and B). I know that the frequency is 1 and there is no bias, also A is between 0 and 1 and B is between [-pi,+pi]. The other things I know: I try to take the least amount of sample points while fitting the curve as well as possible. I also know that the samples tend to be noisy at lower y values (under 0.1 and the lower the noisier).
Previously I used the Math.Net Numerics to fit a A*sin(B+x)+C=y to the samples with linear regression (built the matrix and used QR.Solve on it) and compute the cos^2 from that with trigonometric identities. In that case I took a sample at a random x and every 30 degrees from that for 4 times (so from x to x+480 degree). It didn’t yield significantly worse results than taking samples at every 5 degrees on the same range.

I think (guess) it would give better results if I fit the cos^2 instead of the sine. Can anyone point me in the right direction? I read about the new and shiny Fit.Curve function, but I have no idea how to utilise it in this case.

An easy way, and a hard way.

The easy way would be to model or interpolate your data in some convenient way and find the maximum of your resulting curve. Use that to find B. After than, finding A is pretty easy.

The hard way is to convert your problem from curve fitting to minimum finding by programming an error function. Then use a general purpose non-linear optimizer such as BfgsMinimizer to find your answer. This would require you also program the gradient, basically the partial derivatives with respect to A and B. It could be tricky and might not work, but if you want to go that way, I can give you an example.

If your “few” points are uniformly spaced, consider correlation instead of fitting. “B” can be considered an offset. (Correlation is a form of fitting if you think about it.)

Since you know the frequency, the peak of the correlation (regardless of A) will be the best fit. The location of the peak correlation will give you B.

Once B is found then find A by minimizing the difference between your cosine function and your data at the offset of determined above.