Idea is to multiply two matrix. And do same multiplication using Eigen, then check if result is the same.
In the following making N = 2
returns same thing
but N = 1000
returns NOT same thing
. Why?
#include <cstdlib>
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
const int N = 1000;
void mult_matrix(double x[N][N], double y[N][N], double z[N][N]) {
int rows = N;
int cols = N;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
for (int k = 0; k < cols; k++)
z[i][j] += x[i][k] * y[k][j];
}
void check(double *x, double *y, double *z) {
Matrix<double, Dynamic, Dynamic, RowMajor> m =
Matrix<double, Dynamic, Dynamic, RowMajor>::Map(x, N, N) *
Matrix<double, Dynamic, Dynamic, RowMajor>::Map(y, N, N);
cout << m(0, 0) << endl;
cout << Matrix<double, Dynamic, Dynamic, RowMajor>::Map(z, N, N)(0, 0) << endl;
if (m == Matrix<double, Dynamic, Dynamic, RowMajor>::Map(z, N, N))
cout << "same thing" << endl;
else
cout << "NOT same thing" << endl;
}
int main() {
double *a = (double*)malloc(N*N*sizeof(double));
double *b = (double*)malloc(N*N*sizeof(double));
double *c = (double*)malloc(N*N*sizeof(double));
Matrix<double, Dynamic, Dynamic, RowMajor>::Map(a, N, N).setRandom();
Matrix<double, Dynamic, Dynamic, RowMajor>::Map(b, N, N).setRandom();
Matrix<double, Dynamic, Dynamic, RowMajor>::Map(c, N, N).setZero();
mult_matrix((double (*)[N])a, (double (*)[N])b, (double (*)[N])c);
check(a, b, c);
}
isApprox()
is better than any hand-crafted solution. – Slink