I need to get a n-degree function from n+1 data points. By using the following gnuplot script I get the right fitting:
f(x) = a + b*x + c*x**2 + d*x**3 + e*x**4 + f*x**5 + g*x**6 + h*x**7 + i*x**8 + j*x**9 + k*x**10 + l*x**11 + m*x**12
# Initial values for parameters
a = 0.1
b = 0.1
c = 0.1
d = 0.1
e = 0.1
f = 0.1
g = 0.1
h = 0.1
i = 0.1
j = 0.1
k = 0.1
l = 0.1
m = 0.1
# Fit f to the following data by modifying the variables a, b, c
fit f(x) '-' via a, b, c, d, e, f, g, h, i, j, k, l, m
4.877263 45.036000
4.794907 44.421000
4.703827 43.808000
4.618065 43.251000
4.530520 42.634000
4.443111 42.070000
4.357077 41.485000
4.274298 40.913000
4.188404 40.335000
4.109381 39.795000
4.027594 39.201000
3.946413 38.650000
3.874360 38.085000
e
After fitting, I got the following coefficients:
a = -781956
b = -2.52463e+06
c = 2.75682e+06
d = -553791
e = 693880
f = -1.51285e+06
g = 1.21157e+06
h = -522243
i = 138121
j = -23268.8
k = 2450.79
l = -147.834
m = 3.91268
Then, by plotting data and f(x) together it seems that the given coefficients are right:
However, I need to get such fitting by using c code. For several cases, the GNU Scientific Library code for polynomial fit (as in this link) resulted right. But for the above data (and several other cases in my data set) the result I got was flawed.
For instance, the following code (which uses the same data from the e.g. above):
void testOfPolynomialFit(){
double x[13] = {4.877263, 4.794907, 4.703827, 4.618065, 4.530520, 4.443111, 4.357077, 4.274298, 4.188404, 4.109381, 4.027594, 3.946413, 3.874360};
double y[13] = {45.036000, 44.421000, 43.808000, 43.251000, 42.634000, 42.070000, 41.485000, 40.913000, 40.335000, 39.795000, 39.201000, 38.650000, 38.085000};
double coefficients[13];
polynomialfit(13, 13, x, y, coefficients);
int i, n = 13;
for (i = 0; i < n; i++)
{
printf("%lf\t", coefficients[i]);
}
printf("\n");
}
Results in:
-6817581083.803348 12796304366.105989 -9942834843.404181 3892080279.353104
-630964566.517794 -75914607.005088 49505072.518952 -5062100.000931
-1426228.491628 514259.312320 -70903.844354 4852.824607
-136.738756
Which corresponds to a function in the form:
c(x)=-6837615134.799868+12834646330.586414*x**1-9973474377.668280*x**2+3904659818.834625*x**3-633282611.288889*x**4-76066283.747942*x**5+49670960.939126*x**6-5091123.449217*x**7-1426628.818192*x**8+515175.778491*x**9-71055.177018*x**10+4863.969973*x**11-137.065848*x**12
One can check how c(x) looks like here:
In such image, a(x) and b(x) are functions fitted using "polynomialfit" for just a few of the points (4 and 7).
So, any tips on what I'm doing wrong here? There is some other c code which provides the right fitting?