/***************************************************************************
**
**  This file is part of QGpCoreMath.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2009-07-01
**  Copyright: 2009-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <math.h>
#include <limits>

#include "Statistics.h"

namespace QGpCoreMath {

  /*!
    \class Statistics Statistics.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  void Statistics::add(double val)
  {
    _sum+=val;
    _sum2+=val*val;
    _count++;
  }

  void Statistics::addLog(double val)
  {
    val=log(val);    // Geometric average can be computed
                     // without the log but only multiplications
                     // However the standard deviation requires
                     // the log of each item... hence better to sum log
    _sum+=val;
    _sum2+=val*val;
    _count++;
  }

  void Statistics::reset()
  {
    _sum=0.0;
    _sum2=0.0;
    _count=0;
  }

  double Statistics::mean() const
  {
    switch(_count) {
    case 0:
      return 0.0;
    case 1:
      return _sum;
    default:
      return _sum/_count;
    }
  }

  double Statistics::meanLog() const
  {
    switch(_count) {
    case 0:
      return 0.0;
    case 1:
      return exp(_sum);
    default:
      return exp(_sum/_count);
    }
  }

  double Statistics::stddev() const
  {
    if(_count<2) {
      return 0.0;
    } else {
      double s=(_sum2-_sum*_sum/_count)/(_count-1);
      if(s<0.0) s=0.0;
      return sqrt(s);
    }
  }

  double Statistics::stddevLog() const
  {
    if(_count<2) {
      return 1.0;
    } else {
      double s=(_sum2-_sum*_sum/_count)/(_count-1);
      if(s<0.0) s=0.0;
      return exp(sqrt(s));
    }
  }

} // namespace QGpCoreMath
