A nifty way to do it if the function you're trying to fit has an analytical derivative is this:
Create a stepped approximation to the derivative of the function you're trying to fit; in this case find a stepped approximation to a cosine.
Integrate the stepped approximation and you will get a linear segment approximation.
The slopes of the linear segments are, of course, the values of the steps. The start and finish point of each linear segment is the same as the start and finish of each associated step.
It may not be the exact minimum error fit, but it's really fast to compute and it's good enough for the sort of thing the OP wants. If you want better accuracy, generate more steps.
See the graphic over on ABSE.