Code: Select all
// Lagrangian multipliers using higher-order functions
Function<double, double> f1 = [](double x) { return x; };
Function<double, double> f2 = [](double x) { return x*x; };
Function<double, double> f3 = [&](double x) { return f2(x)*f2(x); };
std::vector<double> lambda = { 0.25, 0.5, 0.25 };
FunctionSet<double, double> funSet = { lambda[0] * f1, lambda[1] * f2, lambda[2] * f3 };
Function<double, double> funSum = Sum(funSet);
std::cout << funSum(5.0) << '\n'; // 170
Function<double, double> f4 = [](double x) { return std::exp(x); };
auto funSum2 = f4 + funSum;
std::cout << funSum2(5.0) << '\n'; // 318.413
[img]//%20Lagrangian%20multipliers%20using%20higher-order%20functions%20 Function<double,%20double>%20f1%20=%20[](double%20x)%20{%20return%20x;%20};%20 Function<double,%20double>%20f2%20=%20[](double%20x)%20{%20return%20x*x;%20};%20 Function<double,%20double>%20f3%20=%20[&](double%20x)%20{%20return%20f2(x)*f2(x);%20};%20 std::vector<double>%20lambda%20=%20{%200.25,%200.5,%200.25%20};%20 FunctionSet<double,%20double>%20funSet%20=%20{%20lambda[0]%20*%20f1,%20lambda[1]%20*%20f2,%20lambda[2]%20*%20f3%20};%20%20 Function<double,%20double>%20funSum%20=%20Sum(funSet);%20 std::cout%20<<%20funSum(5.0)%20<<%20'\n';%20//%20170%20%20 Function<double,%20double>%20f4%20=%20[](double%20x)%20{%20return%20std::exp(x);%20};%20 auto%20funSum2%20=%20f4%20+%20funSum;%20%20 std::cout%20<<%20funSum2(5.0)%20<<%20'\n';%20//%20318.413[/img]