Skip to content

Commit

Permalink
refactor: split mean calculation from result caching
Browse files Browse the repository at this point in the history
  • Loading branch information
Swiftb0y committed Oct 31, 2024
1 parent 2e2f9e6 commit 564de1f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/util/movinginterquartilemean.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ double MovingInterquartileMean::insert(double value) {
// needed using the first std::lower_bound
m_queue.push(value);

m_bChanged = true;

DEBUG_ASSERT(std::is_sorted(m_list.cbegin(), m_list.cend()));

return mean();
// no need to set m_bChanged and check m_list.empty().
// we know the preconditions are satisfied so call `calcMean()` directly
m_dMean = calcMean();
return m_dMean;
}

void MovingInterquartileMean::clear() {
Expand All @@ -45,20 +46,26 @@ double MovingInterquartileMean::mean() {
if (!m_bChanged || m_list.empty()) {
return m_dMean;
}
m_dMean = calcMean();
m_bChanged = false;
return m_dMean;
}

double MovingInterquartileMean::calcMean() const {
// assumes m_list is not empty
auto simpleMean = [](auto begin, auto end) -> double {
double size = std::distance(begin, end);
return std::accumulate(begin, end, 0.0) / size;
};

const auto listSize = m_list.size();
if (listSize <= 4) {
m_dMean = simpleMean(m_list.cbegin(), m_list.cend());
return simpleMean(m_list.cbegin(), m_list.cend());
} else if (listSize % 4 == 0) {
std::size_t quartileSize = listSize / 4;
auto start = m_list.cbegin() + quartileSize;
auto end = m_list.cend() - quartileSize;
m_dMean = simpleMean(start, end);
return simpleMean(start, end);
} else {
// http://en.wikipedia.org/wiki/Interquartile_mean#Dataset_not_divisible_by_four
double quartileSize = listSize / 4.0;
Expand All @@ -73,9 +80,6 @@ double MovingInterquartileMean::mean() {
d_sum += *it;
}
d_sum += *it * quartileWeight;
m_dMean = d_sum / interQuartileRange;
return d_sum / interQuartileRange;
}
m_bChanged = false;

return m_dMean;
}
1 change: 1 addition & 0 deletions src/util/movinginterquartilemean.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class MovingInterquartileMean {
}

private:
double calcMean() const;
// The list keeps input doubles ordered by value.
std::vector<double> m_list;
// The queue keeps a second copy of the list, but in insertion
Expand Down

0 comments on commit 564de1f

Please sign in to comment.