Simple Curve Fitting Implimentation in C++ (SVD Least Sqares Fit or similar)

Shawn Tabrizi picture Shawn Tabrizi · Jun 27, 2012 · Viewed 19k times · Source

I have been scouring the internet for quite some time now, trying to find a simple, intuitive, and fast way to approximate a 2nd degree polynomial using 5 data points.

I am using VC++ 2008.

I have come across many libraries, such as cminipack, cmpfit, lmfit, etc... but none of them seem very intuitive and I have had a hard time implementing the code.

Ultimately I have a set of discrete values put in a 1D array, and I am trying to find the 'virtual max point' by curve fitting the data and then finding the max point of that data at a non-integer value (where an integer value would be the highest accuracy just looking at the array).

Anyway, if someone has done something similar to this, and can point me to the package they used, and maybe a simple implementation of the package, that would be great!

I am happy to provide some test data and graphs to show you what kind of stuff I'm working with, but I feel my request is pretty straightforward. Thank you so much.

EDIT: Here is the code I wrote which works! http://pastebin.com/tUvKmGPn

change size to change how many inputs are used

0 0 1 1 2 4 4 16 7 49

a: 1 b: 0 c: 0 Press any key to continue . . .

Thanks for the help!

Answer

mathematician1975 picture mathematician1975 · Jun 27, 2012

Assuming that you want to fit a standard parabola of the form

    y = ax^2 + bx + c 

to your 5 data points, then all you will need is to solve a 3 x 3 matrix equation. Take a look at this example http://www.personal.psu.edu/jhm/f90/lectures/lsq2.html - it works through the same problem you seem to be describing (only using more data points). If you have a basic grasp of calculus and are able to invert a 3x3 matrix (or something nicer numerically - which I am guessing you do given you refer specifically to SVD in your question title) then this example will clarify what you need to do.