contrib/mul/mbl/mbl_sum_1d.cxx
Go to the documentation of this file.
00001 // This is mul/mbl/mbl_sum_1d.cxx
00002 #include "mbl_sum_1d.h"
00003 //:
00004 // \file
00005 // \brief Computes sum and mean of 1D variable.
00006 // \author Tim Cootes
00007 
00008 #include <vcl_cmath.h>
00009 #include <vcl_iostream.h>
00010 
00011 mbl_sum_1d::mbl_sum_1d()
00012 {
00013   clear();
00014 }
00015 
00016 void mbl_sum_1d::clear()
00017 {
00018   n_obs_ = 0;
00019   sum_ = 0;
00020 }
00021 
00022 mbl_sum_1d& mbl_sum_1d::operator+=(const mbl_sum_1d& s1)
00023 {
00024   sum_ += s1.sum();
00025   n_obs_ += s1.nObs();
00026   return *this ;
00027 }
00028 
00029 const double MAX_ERROR = 1.0e-8;
00030 
00031 //: Test for equality
00032 bool mbl_sum_1d::operator==(const mbl_sum_1d& s) const
00033 {
00034   return n_obs_==s.nObs() &&
00035          vcl_fabs(sum_-s.sum())<MAX_ERROR;
00036 }
00037 
00038 //: Version number for I/O
00039 short mbl_sum_1d::version_no() const
00040 {
00041   return 1;
00042 }
00043 
00044 void mbl_sum_1d::b_write(vsl_b_ostream& bfs) const
00045 {
00046   vsl_b_write(bfs,version_no());
00047   vsl_b_write(bfs,n_obs_);
00048   vsl_b_write(bfs,sum_);
00049 }
00050 
00051 void mbl_sum_1d::b_read(vsl_b_istream& bfs)
00052 {
00053   if (!bfs) return;
00054 
00055   short file_version_no;
00056   vsl_b_read(bfs,file_version_no);
00057 
00058   switch (file_version_no)
00059   {
00060    case 1:
00061     vsl_b_read(bfs,n_obs_);
00062     vsl_b_read(bfs,sum_);
00063     break;
00064    default:
00065     vcl_cerr << "I/O ERROR: mbl_sum_1d::b_read(vsl_b_istream&)\n"
00066              << "           Unknown version number "<< file_version_no << '\n';
00067     bfs.is().clear(vcl_ios::badbit); // Set an unrecoverable IO error on stream
00068     return;
00069   }
00070 }
00071 
00072 void mbl_sum_1d::print_summary(vcl_ostream& os) const
00073 {
00074   os << "mbl_sum_1d: ";
00075   if (n_obs_==0)
00076     os << "No samples.";
00077   else
00078   {
00079     os << "mean: "<< mean() <<" N:"<<n_obs_;
00080   }
00081 }
00082 
00083 vcl_ostream& operator<<(vcl_ostream& os, const mbl_sum_1d& stats)
00084 {
00085   stats.print_summary(os);
00086   return os;
00087 }
00088 
00089   //: Stream output operator for class reference
00090 void vsl_print_summary(vcl_ostream& os,const mbl_sum_1d& stats)
00091 {
00092   stats.print_summary(os);
00093 }
00094 
00095 mbl_sum_1d operator+(const mbl_sum_1d& s1, const mbl_sum_1d& s2)
00096 {
00097   mbl_sum_1d r = s1;
00098   r+=s2;
00099 
00100   return r;
00101 }
00102 
00103   //: Binary file stream output operator for class reference
00104 void vsl_b_write(vsl_b_ostream& bfs, const mbl_sum_1d& b)
00105 {
00106   b.b_write(bfs);
00107 }
00108 
00109   //: Binary file stream input operator for class reference
00110 void vsl_b_read(vsl_b_istream& bfs, mbl_sum_1d& b)
00111 {
00112   b.b_read(bfs);
00113 }