设所求插值函数$f(x)$,是一个$m$次多项式$P_m(x)$
$$ P_m(x)=a_0+a_1x+\cdots+a_mx^m=\sum_{j=0}^ma_jx^j, $$
通过选取多项式的系数$a_j$
$$ \color{red}{\sum_{i=1}^n{\delta_i}^2=\sum_{i=1}^n[y_i-P_m(x_i)]^2=F(a_0,a_1,\cdots,a_m)} $$
使上列式子最小。
def linear_fitting(data_x, data_y):
size = len(data_x);
i = 0
sum_xy = 0
sum_y = 0
sum_x = 0
sum_square_x = 0
while i < size:
sum_xy += data_x[i]*data_y[i];
sum_y += data_y[i]
sum_x += data_x[i]
sum_square_x += data_x[i]*data_x[i]
i += 1
return_a1 = (size*sum_xy-sum_x*sum_y)/(size*sum_square_x-sum_x*sum_x)
return_a0 = (sum_y*sum_square_x-sum_x*sum_xy)/(size*sum_square_x-sum_x*sum_x)
return [return_a1, return_a0]
# 返回多项式的系数这里用来拟合的多项式只有两项