title: Solving Systems of Linear Equations using Eigen
body: <p>I'm currently working on a fluid simulation in C++, and part of the algorithm is to solve a sparse system of linear equations. People recommended using the library Eigen for this. I decided to test it out using this short program that I wrote:</p>
  
  <pre><code>#include &lt;Eigen/SparseCholesky&gt;
  
  #include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  int main() {
      std::vector&lt;Eigen::Triplet&lt;double&gt;&gt; triplets;
      triplets.push_back(Eigen::Triplet&lt;double&gt;(0, 0, 1));
      triplets.push_back(Eigen::Triplet&lt;double&gt;(0, 1, -2));
      triplets.push_back(Eigen::Triplet&lt;double&gt;(1, 0, 3));
      triplets.push_back(Eigen::Triplet&lt;double&gt;(1, 1, -2));
  
      Eigen::SparseMatrix&lt;double&gt; A(2, 2);
      A.setFromTriplets(triplets.begin(), triplets.end());
  
      Eigen::VectorXd b(2);
      b[0] = -2;
      b[1] = 2;
  
      Eigen::SimplicialCholesky&lt;Eigen::SparseMatrix&lt;double&gt;&gt; chol(A);
      Eigen::VectorXd x = chol.solve(b);
  
      std::cout &lt;&lt; x[0] &lt;&lt; ' ' &lt;&lt; x[1] &lt;&lt; std::endl;
  
      system("pause");
  }
  </code></pre>
  
  <p>It gives it these two equations:</p>
  
  <p>x - 2y = -2</p>
  
  <p>3x - 2y = 2</p>
  
  <p>The correct solution is:</p>
  
  <p>x = 2</p>
  
  <p>y = 2</p>
  
  <p>But the problem is that when the program runs, it outputs:
  0.181818 -0.727273</p>
  
  <p>Which is totally wrong! I have been debugging this for hours, but it's a very short program and I'm following the tutorial on the Eigen website exactly. Does anybody know what is causing this issue?</p>
  
  <p>P.S. I know that the classes I'm using are for sparse matrices, but the only difference between those and the normal Matrix classes is the way the elements are stored.</p>