Just a bit of cautionary advice. Using the Fourier series makes sense if you think that your basic function has a cosine series as the basis; however, if you use it as the basis for an arbitrary function (with an unknown shape), you can try to guess a more specific basic type of function (polynomial, exponential, etc.).
I did some limited optimization on such a series, and the function was so distorted that it was hard to say if my fit was significant; my matching function had a large number of local maxima.
source share