Skip to content

Commit

Permalink
Merge pull request asutton#8 from tshev/master
Browse files Browse the repository at this point in the history
Adding 2 functions: moving_sums and moving_means
  • Loading branch information
asutton committed May 9, 2016
2 parents f13bea1 + 4b7ad0d commit abe171f
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/origin.math/moving_means.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include <origin.math/stats.hpp>
#include <iostream>
int main() {
std::vector<double> values = {1, 2, 3, 4, 5, 6};
auto f = std::begin(values);
auto l = std::end(values);
for (auto x : origin::moving_means(f, f + 2, l)) {
std::cout << x << std::endl;
}
}
Binary file added examples/origin.math/moving_sums
Binary file not shown.
15 changes: 15 additions & 0 deletions examples/origin.math/moving_sums.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <origin.math/stats.hpp>
#include <iostream>
#include <iterator>

int main() {
std::vector<double> values = {1, 2, 3, 4, 5, 6};
auto f = std::begin(values);
auto l = std::end(values);
std::vector<int> result;
origin::moving_sums(f, f + 2, l, std::back_inserter(result), 0.0);
for (auto x : result) {
std::cout << x << std::endl;
}
return 0;
}
50 changes: 50 additions & 0 deletions origin.math/stats.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,56 @@ template<typename I, typename T = Value_type<I>>
return sum(first, last) / distance(first, last);
}

template<
typename It, typename Out,
typename T = typename std::iterator_traits<It>::value_type
>
// requires(ForwardIterator(It))
// required(OutputIterator(Out))
// <T, +> is a group
// r -= a && r += a <=> r = r - a && r = r + a
// -= implies + inverse element
Out moving_sums(It f, It m, It l, Out out, T acum) {
auto it = f;
while(it != m) {
acum += *it;
it++;
}

*out = acum;
out++;
while (it != l) {
acum -= *f;
acum += *it;
*out = acum;

out++;
it++;
f++;
}
return out;
}

template<
typename It,
typename T = typename std::iterator_traits<It>::value_type
>
// requires(ForwardIterator(It)
// required(OutputIterator(Out)
// <T, +> is a group
inline
std::vector<T> moving_means(It f, It m, It l) {
auto window_length = std::distance(f, m);
auto length = std::distance(f, l);
std::vector<T> result(length - window_length + 1);
moving_sums(f, m, l, std::begin(result), T(0));
for (auto &x : result) {
x /= window_length;
}
return result;
}


template<typename I, typename T = Value_type<I>>
inline T
geometric_mean(I first, I last) {
Expand Down

0 comments on commit abe171f

Please sign in to comment.