]> AND Private Git Repository - loba.git/blob - cost_func.cpp
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
Cosmetics: rename message types, INFO -> CTRL, and LOAD -> DATA.
[loba.git] / cost_func.cpp
1 #include <algorithm>
2 #include <functional>
3 #include <numeric>
4 #include <iterator>
5 #include <sstream>
6 #include <stdexcept>
7
8 #include "cost_func.h"
9
10 cost_func::cost_func(const char* param)
11 {
12     std::istringstream paramstream(param);
13     std::string token;
14     while (std::getline(paramstream, token, ',')) {
15         std::istringstream str(token);
16         double f;
17         if ((str >> f) && str.eof())
18             factors.push_back(f);
19         else
20             throw std::invalid_argument("cost_func(): "
21                                         "cannot parse \"" + token + "\"");
22     }
23     if (factors.empty())
24         throw std::invalid_argument("cost_func(): no factor");
25 }
26
27 cost_func::~cost_func()
28 {
29 }
30
31 double cost_func::operator()(double amount) const
32 {
33     using std::placeholders::_1;
34     using std::placeholders::_2;
35     return std::accumulate(++factors.begin(), factors.end(), factors.front(),
36                            std::bind(std::plus<double>(),
37                                      std::bind(std::multiplies<double>(),
38                                                amount, _1), _2));
39 }
40
41 std::string cost_func::to_string()
42 {
43     std::ostringstream oss;
44     std::copy(factors.begin(), --factors.end(),
45               std::ostream_iterator<double>(oss, ", "));
46     oss << factors.back();
47     return oss.str();
48 }
49
50 // Local Variables:
51 // mode: c++
52 // End: