I am a complete newbie to c++ and programming in general. I need to write something for scientific purposes and as such, performance is crucial. I introduced two types, matrices and vectors with intervals as entries, and now want to make them “able to work with”, i.e. define basic operations. The type definitions:
#include <eigen3/Eigen/Dense> #include <boost/numeric/interval.hpp> namespace bn = boost::numeric; namespace bi = bn::interval_lib; // Interval typedefs using Interval = bn::interval< double, bi::policies< bi::save_state<bi::rounded_transc_std<double> >, bi::checking_base<double> > >; using Matrix = Eigen::Matrix<Interval, 3, 3>; using Vector = Eigen::Matrix<Interval, 3, 1>;
Luckily, matrix products work without extra definitions (although I need to call a.lazyProduct(b), otherwise I receive an “operator unambiguous” error, which I don’t understand), but inner products and multiplications with constants do not. It seems that I have to manually overload the multiplications, which I did as follows:
Interval operator* (const double& x, const Interval& y) { double lower(x*y.lower()); double upper(x*y.upper()); if(x>0){ return Interval(lower,upper); } else{ return Interval(upper,lower); } } Vector operator* (const double& x, const Vector& y) { Vector res; for(int i = 0; i<3;i++) { res[i] = x*y[i]; } return res; } Matrix operator* (const double& x, const Matrix& y) { Matrix res; for(int i = 0; i<3; i++) { for(int j = 0; j<3; j++){ res(i,j) = x* y(i,j); } } return res; } Interval inner_prod(const Vector& x, const Vector& y){ Interval res; for(int i = 0; i<3; i++){ res += x[i]*y[i]; } return res; } Interval inner_prod(const std::vector<double>& x, const Vector& y){ Interval res; for(int i = 0; i<3; i++){ res += x[i] * y[i]; } return res; }
sizes are hard-coded as I will not be working with any others. I would love to have some feedback and improvement suggestions that focus on performance. Also for the inner product, I was hoping there was a way to make use of std::inner_product for possible better performance, but I can’t figure out how.