00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include <stdio.h>
00026
00027 #include "leastsqs.hxx"
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043 double sum_xi, sum_yi, sum_xi_2, sum_xi_yi;
00044 int sum_n;
00045
00046 void least_squares(double *x, double *y, int n, double *m, double *b) {
00047 int i;
00048
00049 sum_xi = sum_yi = sum_xi_2 = sum_xi_yi = 0.0;
00050 sum_n = n;
00051
00052 for ( i = 0; i < n; i++ ) {
00053 sum_xi += x[i];
00054 sum_yi += y[i];
00055 sum_xi_2 += x[i] * x[i];
00056 sum_xi_yi += x[i] * y[i];
00057 }
00058
00059
00060
00061
00062 *m = ( (double)sum_n * sum_xi_yi - sum_xi * sum_yi ) /
00063 ( (double)sum_n * sum_xi_2 - sum_xi * sum_xi );
00064 *b = (sum_yi / (double)sum_n) - (*m) * (sum_xi / (double)sum_n);
00065
00066
00067 }
00068
00069
00070
00071 void least_squares_update(double x, double y, double *m, double *b) {
00072 ++sum_n;
00073
00074 sum_xi += x;
00075 sum_yi += y;
00076 sum_xi_2 += x * x;
00077 sum_xi_yi += x * y;
00078
00079
00080
00081
00082 *m = ( (double)sum_n * sum_xi_yi - sum_xi * sum_yi ) /
00083 ( (double)sum_n * sum_xi_2 - sum_xi * sum_xi );
00084 *b = (sum_yi / (double)sum_n) - (*m) * (sum_xi / (double)sum_n);
00085
00086
00087 }
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097 double least_squares_error(double *x, double *y, int n, double m, double b) {
00098 int i;
00099 double error, sum;
00100
00101 sum = 0.0;
00102
00103 for ( i = 0; i < n; i++ ) {
00104 error = y[i] - (m * x[i] + b);
00105 sum += error * error;
00106
00107 }
00108
00109 return ( sum / (double)n );
00110 }
00111
00112
00113
00114
00115
00116
00117
00118 double least_squares_max_error(double *x, double *y, int n, double m, double b){
00119 int i;
00120 double error, max_error;
00121
00122 max_error = 0.0;
00123
00124 for ( i = 0; i < n; i++ ) {
00125 error = y[i] - (m * x[i] + b);
00126 error = error * error;
00127 if ( error > max_error ) {
00128 max_error = error;
00129 }
00130 }
00131
00132 return ( max_error );
00133 }
00134
00135