title: Multiplying a matrix by itself in C++
body: <p>I am trying to simulate Markov chain transitions by multiplying a 2x2 matrix (the transition matrix) by a 2x1 matrix in C++, and then taking that output as a 2x1 matrix and then using it again in a multiplication, repeated again up to a set number of times.</p>
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  int main(void){
  
  // initialize variables
  float trMat1,trMat2,trMat3,trMat4,iniA,iniB;
  int cycle;
  
  // initialize transition matrix
  trMat1 = 0.883; // top left
  trMat2 = 0.259; // top right
  trMat3 = 0.117; // bottom left
  trMat4 = 0.741; // bottom right
  
      cout &lt;&lt; &quot;Enter the product preference for A: &quot;;
      cin &gt;&gt; iniA;
  
      cout &lt;&lt; &quot;Enter the product preference for B: &quot;;
      cin &gt;&gt; iniB;
  
      if(iniA + iniB != 1){
          cout &lt;&lt; &quot;ERROR: Probabilities do not add to 1. Terminating&quot; &lt;&lt; endl;
          return 0;
      }
  
      cout &lt;&lt; &quot;Enter number of cycles to simulate: &quot;;
      cin &gt;&gt; cycle;
  
      cout &lt;&lt; &quot;Simulating... &quot; &lt;&lt; endl;
  
      // matrix multiplication starts
      for(int z = 0; z &lt; cycle; z++){
          iniA = trMat1 * iniA + trMat2 * iniB;
          iniB = trMat3 * iniA + trMat4 * iniB;
      }
      
      cout &lt;&lt; &quot;A (end): &quot;;
      cout &lt;&lt; iniA &lt;&lt; endl;
  
      cout &lt;&lt; &quot;B (end): &quot;;
      cout &lt;&lt; iniB &lt;&lt; endl;
  </code></pre>
  <p>}</p>
  <p>Since these are probabilities, iniA and iniB are meant to add to exactly 1, but they never do (always a little over or under 1 but never exactly). Could this be due to a rounding error or perhaps something else? Thank you.</p>