Files
ResInsight/ApplicationLibCode/Application/Tools/RiaWeightedMeanCalculator.inl
T
Kristian Bendiksen 394bc6c3df #12489 Improve robustness of mean calculators
Replace asserts with early-return guards so zero or negative weights
are silently skipped instead of crashing. Add unit tests for zero-weight
and zero-value edge cases in all three calculator classes.

Fixes #12489.
2026-03-31 08:46:20 +02:00

70 lines
2.6 KiB
C++

/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018- Equinor ASA
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ResInsight 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 General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <class T>
RiaWeightedMeanCalculator<T>::RiaWeightedMeanCalculator()
: m_aggregatedValue( T{} )
, m_aggregatedWeight( 0.0 )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <class T>
void RiaWeightedMeanCalculator<T>::addValueAndWeight( T value, double weight )
{
if ( weight <= 0.0 ) return;
m_aggregatedValue = m_aggregatedValue + value * weight;
m_aggregatedWeight += weight;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <class T>
T RiaWeightedMeanCalculator<T>::weightedMean() const
{
if ( validAggregatedWeight() )
{
return m_aggregatedValue * ( 1.0 / m_aggregatedWeight );
}
return T{};
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <class T>
double RiaWeightedMeanCalculator<T>::aggregatedWeight() const
{
return m_aggregatedWeight;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <class T>
bool RiaWeightedMeanCalculator<T>::validAggregatedWeight() const
{
return m_aggregatedWeight > 1.0e-12;
}