Related
I have:
vector<double> ved1 = { 1,2,3,4,5,6,7,8,9,10 };
vector<double> ved2 = { 11,12,13,14,15,16,17,18,19,20 };
vector<double> ved3(10);
and I want to have ved3=ved3/2 but I can't get it correctly, the result is 2/ved3;
How to use divides?
transform(ved1.begin(), ved1.end(), ved2.begin(), ved3.begin(), plus<double>());
transform(ved3.begin(), ved3.end(), ved3.begin(), bind1st(divides<double>(),2));`
I want cos(ved2), but I cannot get it. What's wrong with my code?
double cos_1(double x) { return cos(x); }
for_each(ved2.begin(), ved2.end(), cos_1);
bind1st will bind 2 to the 1st argument of divides, and then transform will supply each element of ved3 to divides as the second argument. So the result will be divides(2, ved3[0]), divides(2, ved3[1]) and so on.
If you want to calculate divides(ved3[...], 2) instead, use bind2nd(divides<double>(), 2). This way, 2 will be bound to the second argument, leaving the first one vacant for transform.
How to use std::for_each to apply a cosine elementwise
std::for_each does not fill some output; or necessarily change the input container/range. It just applies an invocable object to each element of a range. If the function has no "side effects" - than the for_each would be useless. Specifically, in your case - you're computing the cosine of each value, but not doing anything with it.
If you want to change the values in-place, you'll need to specifically do that:
void apply_cos(double& x) { x = std::cos(x); }
// ...
for_each(ved2.begin(), ved2.end(), apply_cos);
or using a lambda expression:
for_each(ved2.begin(), ved2.end(), [](double& x) { x = cos(x); });
Note the use of a reference input to the function rather than a value: double& x, not double x. That means that when you change x in apply_cos(), the value in the input range to std::for_each changes.
I am learning about Lambda Expressions in C++ although I am not a newcomer to C/C++.
I am having difficulty seeing the relative merits of using the Capture-Clause vs old fashioned parameter passing in the Argument-List to draw variables into the Lambda body for manipulation.
I am familiar with their syntactical differences and what is and is not allowed in each, but just don't see how one is more effective than the other?
If you have insider knowledge, or a better picture of what's going on with Lambdas please let me know.
Many Thanks, Reza.
Consider that lambdas are basically just syntactic sugar for functors. For example
int x = 1;
auto f = [x](int y){ return x+y; };
is more or less equivalent to
struct add_x {
int x;
add_x(int x) : x(x) {}
int operator()(int y) const { return x+y; }
}
int x = 1;
add_x f{x};
And the difference becomes apparent when you pass the lambda around, e.g.
template <typename F>
void foo(F f) {
for (int i=0;i<10;++i) std::cout << f(i) << '\n';
}
Functions like that are one of the main motiviations to use lambdas and it is the function that (in this case only implicitly) specifies the expected signature. You can call foo as
foo(f);
But if your functor / lambda would take also x as parameter then you would not be able to pass it to foo.
TL;DR: Variables that are captured consitute the state of the lambda, while parameters are just like ordinary function parameters.
The difference is that the same capture can be used with different arguments.
Consider the following simple example
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const int N = 10;
for ( const auto &item : a ) std::cout << item << ' ';
std::cout << '\n';
std::transform( std::begin( a ), std::end( a ), std::begin( a ),
[=]( const auto &item ) { return N * item; } );
for ( const auto &item : a ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
The program output is
0 1 2 3 4 5 6 7 8 9
0 10 20 30 40 50 60 70 80 90
the arguments for the lambda are supplied by the algorithm std::transform. The algorithm is unable to pass to the lambda the multiplier N. So you need to capture it and the multiplier will be used with any argument passed to the lambda.
A lambda expression creates a function-like object with some optional additional state. The call signature is determined by the lambda parameters, and the additional state is determined by the capture clause.
Now the signature you need to create is not always your choice. If you are passing your lambda to a standard or third-party API, then the API requires your lambda to have a certain signature. If tgere is any data you want to pass in addition to the imposed signature, you need to capture it.
Consider a well known example from the C library: the qsort function.
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));
The comparator function accepts pointers to the two objects being compared and that's it. There is no way to pass an additional flag that would control how exactly the comparison is done. As an example, consider sorting a list of words in some natural language according to the collation rules of that language, determined at runtime. How do you tell your comparator which language to use? The only option with this API is to set the language in a static variable (yikes).
Because of this well known shortcoming, people are defining various non-standard substitute APIs. For example
void qsort_r(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *, void *),
void *arg);
I hope you recognise what's going on. You pass an additional argument (the language identifier or whatever) as arg, then the sort function forwards it as a sealed package to your comparator. It then casts the argument to its original type and uses it
Enter C++. In std::sort, the comparator is a function like object that carries its own state. So this trick is unnecessary. You define something like
struct LanguageSensitiveComparator
{
LanguageSensitiveComparator(LangauageID lang) : lang(lang) {}
LangauageID lang;
bool operator()(const string& a, const string& b) const { .... } // etc
};
sort(dict.begin(), dict.end(), LanguageSensitiveComparator(lang));
C++11 takes its a step further. Now you can define the function object on the spot, using a lambda.
sort (begin(dict), end(dict),
[=lang](const string& a, const string& b) { .. });
Back to your question. Could you pass lang as an argument instead of capturing it? Sure, but you would need to define your own sort that knows about an additional LabguageID parameter (that's what qsort_r basically does, except it's not type safe).
I would like to compute the function composition -- f ( g (param) ). Here is what I tried:
auto fComposition(auto&& f, auto&& g, auto&&... params)
{
/* some stuff */
auto result = std::forward<decltype(f)>(f)(
std::forward<decltype(g)>(g)(
std::forward<decltype(params)>(param)
)
);
/* other stuff */
return result;
};
Compiling with
g++ -std=c++17 src.cpp
basic test
#include <random>
#include <math.h>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> distr(-1.0, 1.0);
auto xx = fComposition(round, distr, gen);
return 0;
}
I've got the message that it doesn't recognize the type of first function .
BTW, is this really your code? You're not expanding params so it should not compile.
I. The way you define composition, it is indistinguishable from a simple invocation: your fComposition(f, g, arg) is the same as f(g(arg)) except for extra characters typing. The real composition is usually a combinator that accepts two functions and returns a closure that, when invoked on actual arguments, applies them in succession. Something like:
template<class F, class G> auto comp(F f, G g) {
return [f, g](auto &&... args) {
return f(g(std::forward<decltype(args)>(args)...));
};
}
(Note by-values bindings. In C++17, they are more advanced than twenty years ago. :) You can add std::moves and std::forwards by taste.)
This way you compose two functions:
auto fg = comp(f, g);
and later invoke the result on arguments:
auto x = fg(arg1, arg2);
II. But really, why limit ourselves with two operands? In Haskell, (.) is a single binary function. In C++, we can have a whole tree of overloads:
template<class Root, class... Branches> auto comp(Root &&root, Branches &&... branches) {
return [root, branches...](auto &&...args) {
return root(branches(std::forward<decltype(args)>(args)...)...);
};
}
Now you can encapsulate any AST in a single callable:
int f(int x, int y) { return x + y; }
int g(int x) { return x * 19; }
int h(int x) { return x + 2; }
#include <iostream>
int main() {
auto fgh = comp(f, g, h);
std::cout << fgh(2) << '\n';
}
A similar technique was the only way known to me to have anonymous closures in C++ prior to 11 standard.
III. But wait, is there a library solution? In fact, yes. From std::bind's description
If the stored argument arg is of type T for which std::is_bind_expression<T>::value == true (for example, another bind expression was passed directly into the initial call to bind), then bind performs function composition: instead of passing the function object that the bind subexpression would return, the subexpression is invoked eagerly, and its return value is passed to the outer invokable object. If the bind subexpression has any placeholder arguments, they are shared with the outer bind (picked out of u1, u2, ...). Specifically, the argument vn in the std::invoke call above is arg(std::forward<Uj>(uj)...) and the type Vn in the same call is std::result_of_t<T cv &(Uj&&...)>&& (cv qualification is the same as that of g).
Sorry, no examples here at this moment. >_<
P.S. And yes, std::round is an overloaded function so you should typecast it to specify which exactly overload you need to be composed.
The include of random includes cmath, which in libstdc++ also defines several of the math operators (including round) in the default namespace as well as in the std namespace. (See this answer for the rationale.) And C++'s round has multiple overloads. As a result, you have several versions of round available, and your function doesn't know which round you want to use, thus the error message about ambiguity. The correct solution is to disambiguate which round you mean. You can do this with a static cast:
static_cast<double(*)(double)>(round)
Since you have to go through the trouble anyway, you may as well also use the cmath header instead of math.h and use std::round instead. At least then you know that it's going to be overloaded up front.
I wrote a simple implementation of the newton raphson root finding algorithm which takes an initial guess init, a unary function f and the tolerance tol as arguments, as shown below:
bool newton_raphson(double& init,
double(*f)(double),
double tol){
const int max_iter = 10000;
double next_x, soln = init;
int i = 0;
while(++i < max_iter){
next_x = soln - f(soln)/fp_x(f, soln);
if(fabs(next_x - soln) < tol){
init = next_x;
return true;
}
soln = next_x;
}
return false;
}
double fp_x(double(*f)(double),
double x){
const double h = 0.000001;
return (f(x + h) - f(x - h))/2.0/h;
}
My question is: although this works perfectly fine for unary functions, I would like to change the implementation so that it works for functions f that have more than one parameter, but all except one parameter have constant values. To clarify: if I have a function f(x) = 3x + 2 as shown below
double f(double x){
return (3*x + 2);
}
Then my implementation works. However, I would also like it to work for any functions with any given number of arguments, but only the first argument is variable. So, if I have a function f(x,y) = 3x + 2y
double f(double x, double y){
return (3*x + 2*y);
}
I would like to find the root of f(x,2), or f(x,3) using the same function, and so on for n arguments, not just one or two (please ignore the idea that the functions I showed in the example are simple linear functions, this is just an example). Is there any way to implement the function for a varying number of arguments or do I have to write an implementation for every case?
Thanks,
NAX
NOTE
As you could tell by now, this question isn't really about newton-raphson, but it makes it easier if I use it as an example for the actual question, which is a single implementation for functions of different numbers of arguments.
UPDATE
A few answers below use std::bind and std::function to solve the problem, which actually better address my question than the selected answer; however, they are c++11 library classes/functions, (which, don't get me wrong, is something I strongly urge every c++ programmer to go ahead and learn) and at the time of this writing, I was facing some problems using them; Eclipse Juno using g++ 4.7 (which is c++11 compliant) still somehow failed to recognize std::function, and I therefore decided to go and stick with the checked answer below, which also works nicely.
I think you're asking for variadic functions:
A variadic function – a function declared with a parameter list ending
with ellipsis (...) – can accept a varying number of arguments of
differing types. Variadic functions are flexible, but they are also
hazardous. The compiler can't verify that a given call to a variadic
function passes an appropriate number of arguments or that those
arguments have appropriate types. Consequently, a runtime call to a
variadic function that passes inappropriate arguments yields undefined
behavior. Such undefined behavior could be exploited to run arbitrary
code.
From here:
https://www.securecoding.cert.org/confluence/display/cplusplus/DCL31-CPP.+Do+not+define+variadic+functions
However, as quoted above, there are a number of problems with them.
Most notably, it only works for compile time!
However, if you are interested in implementing one, here's an article with a nice example:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=138
UPDATE:
IMO, I think you're better off defining functions that take structure or object arguments (i.e. a general function object), and writing functions that work on those arguments explicitly.
The other option is to do some compile-time reflection - which would be useful, but is too much trouble to do in such an example as this. Plus, "reflection" in C++ isn't "true" reflection, but rather a bad and incomplete implementation of it.
For what you're trying to do here, what you're looking for is std::bind (or, if you're dealing with a C++03 compiler, std::bind1st and std::bnd2nd).
These will let you "bind" values to the other parameters, leaving you with a function (technically, a function object) that only requires a single parameter.
What you'd ideally like would be something like this:
double f(double x, double y) {
return 3*x + 2*y;
}
double init = 1.0;
newton_raphson(init, std::bind2nd(f, 3), 1e-4);
Unfortunately, in real use, it's not quite that simple -- to work with std::bind2nd, you can't use an actual function; you need to use a function object instead, and it has to derive from std::binary_function.
std::bind is quite a bit more flexible, so that's what you almost certainly want to use instead (if at all possible).
I used your question as a way to force myself to learn C++11 variadic template, here is a working example.
template< typename... Ts >
double f( Ts... Vs ) {
double array[] = { Vs... };
int numArg = sizeof...( Vs );
switch (numArg) {
case 1:
return 3 * array[0] + 2;
case 2:
return 3 * array[0] + 2 * array[1];
case 3:
return 3 * array[0] + 2 * array[1] + 1 * array[3];
....
default:
return 0.0;
}
}
template< typename... Ts >
double newton_raphson( double &init, double tol,
double (*func) ( Ts... Vs ), Ts... Vs ) {
return func( Vs... );
}
you can call it like
newton_raphson( &init, 1.0, f, 1.0, 2.0, 3.0, 4.0, 5.0 );
You can use std::bind and std::function. The type std::function<double(double)> represents a functional that takes in a double and returns a double. Similarly std::function<double(int,int)> is for a functional taking 2 ints and returns a double.
#include <functional>
bool newton_raphson(double& init,
std::function<double(double)>& f,
double tol){
const int max_iter = 10000;
double next_x, soln = init;
int i = 0;
while(++i < max_iter){
next_x = soln - f(soln)/fp_x(f, soln);
if(fabs(next_x - soln) < tol){
init = next_x;
return true;
}
soln = next_x;
}
return false;
}
double myfunction(double x, double y){
return (3*x + 2*y);
}
double fp_x(std::function<double(double)> f, double x) {
...
}
...
double d = 1.0;
// Here we set y=2.5 and we tell bind that 1st parameter is unbounded
// If we wanted to switch and set x=2.5 and let y be unbounded, then
// we would use (&myfunction, 2.5, std::placeholders::_1)
newton_raphson(d, std::bind(&myfunction, std::placeholders::_1, 2.5) , 1e-6);
...
I was working on my advanced calculus homework today and we're doing some iteration methods along the lines of newton's method to find solutions to things like x^2=2. It got me thinking that I could write a function that would take two function pointers, one to the function itself and one to the derivative and automate the process. This wouldn't be too challenging, then I started thinking could I have the user input a function and parse that input (yes I can do that). But can I then dynamically create a pointer to a one-variable function in c++. For instance if x^2+x, can I make a function double function(double x){ return x*x+x;} during run-time. Is this remotely feasible, or is it along the lines of self-modifying code?
Edit:
So I suppose how this could be done if you stored the information in an array and that had a function that evaluated the information stored in this array with a given input. Then you could create a class and initialize the array inside of that class and then use the function from there. Is there a better way?
As others have said, you cannot create new C++ functions at runtime in any portable way. You can however create an expression evaluator that can evaluate things like:
(1 + 2) * 3
contained in a string, at run time. It's not difficult to expand such an evaluator to have variables and functions.
You can't dynamically create a function in the sense that you can generate raw machine code for it, but you can quite easily create mathematical expressions using polymorphism:
struct Expr
{
virtual double eval(double x) = 0;
};
struct Sum : Expr
{
Sum(Expr* a, Expr* b):a(a), b(b) {}
virtual double eval(double x) {return a->eval(x) + b->eval(x);}
private:
Expr *a, *b;
};
struct Product : Expr
{
Product(Expr* a, Expr* b):a(a), b(b) {}
virtual double eval(double x) {return a->eval(x) * b->eval(x);}
private:
Expr *a, *b;
};
struct VarX : Expr
{
virtual double eval(double x) {return x;}
};
struct Constant : Expr
{
Constant(double c):c(c) {}
virtual double eval(double x) {return c;}
private:
double c;
};
You can then parse your expression into an Expr object at runtime. For example, x^2+x would be Expr* e = new Sum(new Product(new VarX(), new VarX()), new VarX()). You can then evaluate that for a given value of x by using e->eval(x).
Note: in the above code, I have ignored const-correctness for clarity -- you should not :)
It is along the lines of self-modifying code, and it is possible—just not in "pure" C++. You would need to know some assembly and a few implementation details. Without going down this road, you could abstractly represent operations (e.g. with functors) and build an expression tree to be evaluated.
However, for the simple situation of just one variable that you've given, you'd only need to store coefficients, and you can evaluate those for a given value easily.
// store coefficients as vector in "reverse" order, e.g. 1x^2 - 2x + 3
// is stored as [3, -2, 1]
typedef double Num;
typedef vector<double> Coeffs;
Num eval(Coeffs c, Num x) {
assert(c.size()); // must not be empty
Num result = 0;
Num factor = 1;
for (Coeffs::const_iterator i = c.begin(); i != c.end(); ++i) {
result += *i * factor;
factor *= x;
}
return result;
}
int main() {
Coeffs c; // x^2 + x + 0
c.push_back(0);
c.push_back(1);
c.push_back(1);
cout << eval(c, 0) << '\n';
cout << eval(c, 1) << '\n';
cout << eval(c, 2) << '\n';
}
You don't really need self modifiying code for that. But you will be writing what comes down to an expression parser and interpreter. You write the code to parse your function into suitable data structures (e.g. trees). For a given input you now traverse the tree and calculate the result of the function. Calculation can be done through a visitor.
You don't need to know assembly. Write c++ code for the possible expressions, and then write a compiler which examines the expression and choose the appropriate code snippets. That could be done at runtime like an interpreter usually does, or it could be a compile phase which creates code to execute by copying the instructions from each expression evaluation into allocated memory and then sets it up as a function. The latter is harder to understand and code, but will perform better. But for the development time plus execution time to be less than an interpreted implementation, the compiled code would have to be used lots (billions) of times.
As others have mentioned. Writing self-modifying code isn't necessary at all and is painfull in a compiled language if you want it to be portable.
The hardest part of your work is parsing the input. I recommend muParser to evaluate your expressions. It should take away a lot of pain and you would be able to focus on the important part of your project.