include/trace-tools/tool/linear_regression.hxx

00001 /*
00002  * trace-tools - A library and a set of tools to manipulate wireless traces.
00003  * Copyright (C) 2007  Universite Pierre et Marie Curie - Paris 6
00004  *
00005  * This program is free software; you can redistribute it and/or modify
00006  * it under the terms of the GNU General Public License as published by
00007  * the Free Software Foundation; either version 2 of the License, or
00008  * (at your option) any later version.
00009  *
00010  * This program is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  * GNU General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU General Public License
00016  * along with this program; if not, write to the Free Software
00017  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
00018  * MA  02110-1301  USA
00019  *
00020  * Author: Thomas Claveirole <thomas.claveirole@lip6.fr>
00021  */
00022 #ifndef TOOL_LINEAR_REGRESSION_HXX_
00023 # define TOOL_LINEAR_REGRESSION_HXX_
00024 
00025 # include <gmpxx.h>
00026 
00027 # include "linear_regression.hh"
00028 
00029 namespace tool
00030 {
00031 
00032   template <class ImplType, class InputIterator>
00033   std::pair<ImplType, ImplType>
00034   linear_regression(const InputIterator& first,
00035                     const InputIterator& last)
00036   {
00037     typename InputIterator::difference_type     n = 0;
00038     ImplType                                    x_mean (0);
00039     ImplType                                    y_mean (0);
00040 
00041     for (InputIterator i = first; i != last; ++i)
00042       {
00043         y_mean += i->first;
00044         x_mean += i->second;
00045         ++n;
00046       }
00047     y_mean /= n;
00048     x_mean /= n;
00049 
00050     ImplType            cov (0);
00051     ImplType            V_x (0);
00052 
00053     for (InputIterator i = first; i != last; ++i)
00054       {
00055         const ImplType  y_diff = i->first - y_mean;
00056         const ImplType  x_diff = i->second - x_mean;
00057 
00058         cov += y_diff * x_diff;
00059         V_x += x_diff * x_diff;
00060       }
00061     cov /= n;
00062     V_x /= n;
00063 
00064     const ImplType      a = cov / V_x;
00065     const ImplType      b = y_mean - a * x_mean;
00066 
00067     return std::make_pair(a, b);
00068   }
00069 
00070 } // End of namespace tool.
00071 
00072 #endif // ! TOOL_LINEAR_REGRESSION_HXX_

Generated on Wed Sep 12 16:02:47 2007 for trace-tools by  doxygen 1.5.3