This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Best way to implement the Rosenbrock function?

Tags: None
(comma "," separated)
bravegag
Registered Member
Posts
52
Karma
0
Hello,

What would be the fastest and most elegant way to implement the Rosenbrock function using Eigen in vectorized form ofc?

The Rosenbrock function can be seen here (it is the third one):
https://en.wikipedia.org/wiki/Test_func ... timization
or here (second sum formula the one that has "A more involved variant is")
https://en.wikipedia.org/wiki/Rosenbroc ... alisations

My implementation is this but maybe there is a better gymnastic?

Code: Select all
inline double pow2(double x) {
   return x * x;
}

static std::tuple<double, VectorXd> rosenbrockObjective(const VectorXd& x) {
  VectorXd x1 = x.topRows   (x.rows() - 1);
  VectorXd x2 = x.bottomRows(x.rows() - 1);
  return  = ((x2 - x1.unaryExpr(ptr_fun(pow2))).array().square() + (x1.array() - 1.0).square()).sum();
}


Many TIA,
Best regards,
Giovanni
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Use head/tail for vectors, .square instead of calling pow2, and Ref<> to avoid copies, e.g.:
Code: Select all
static std::tuple<double, VectorXd> rosenbrockObjective(Ref<const ArrayXd> x) {
  Ref<const ArrayXd> x1 = x.head   (x.rows() - 1);
  Ref<const ArrayXd> x2 = x.tail(x.rows() - 1);
  return  = ((x2 - x1.square()).square() + (x1 - 1.0).square()).sum();
}
bravegag
Registered Member
Posts
52
Karma
0
ggael wrote:Use head/tail for vectors, .square instead of calling pow2, and Ref<> to avoid copies, e.g.:
Code: Select all
static std::tuple<double, VectorXd> rosenbrockObjective(Ref<const ArrayXd> x) {
  Ref<const ArrayXd> x1 = x.head   (x.rows() - 1);
  Ref<const ArrayXd> x2 = x.tail(x.rows() - 1);
  return  = ((x2 - x1.square()).square() + (x1 - 1.0).square()).sum();
}


impressive! I get a 2x speed up with your version.

Thank you so much!

Best regards,
Giovanni


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], q.ignora, watchstar