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:
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(0.0);
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(0.0);
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.
The boost/numeric/interval.hpp
header gives a definition for multiplication of intervals with scalars, I must have made some mistake before that this didn't work. That just leaves my custom types.
std::array<double, 3>
rather thanstd::vector
. That'll save some bytes which store the size instd::vector
. \$\endgroup\$#include <eigen3/Eigen/Dense>
I think you are supposed to write#include <Eigen/Dense>
and compile with a suitable-I
flag. \$\endgroup\$