title: C# to mimic Excel SLOPE function
body: <p>I'm trying to calculate the slope of two data lists. You can easily calculate this in EXCEL using the SLOPE function. <code>=SLOPE(A1:A100, B1:B100)</code>. I'm trying to mimic this function in C# WinForm. Here is my code, it can calculate something, but not the correct number that you would get from the Excel function. Please help me find the error here. Thanks so much!</p>
  
  <pre><code>private double Getslope(List&lt;double&gt; ProductGrossExcessReturnOverRFR, List&lt;double&gt; primaryIndexExcessReturnOverRFR, int months, int go_back = 0)
  {
      double slope = 0;
      double sumx = 0, sumy = 0, sumxy = 0, sumx2 = 0;
      for (int i = ProductGrossExcessReturnOverRFR.Count - 1 - go_back; i &gt; ProductGrossExcessReturnOverRFR.Count - (1 + months + go_back); i--)
      {
          sumxy += ProductGrossExcessReturnOverRFR[i] * primaryIndexExcessReturnOverRFR[i];
          sumx += ProductGrossExcessReturnOverRFR[i];
          sumy += primaryIndexExcessReturnOverRFR[i];
          sumx2 += ProductGrossExcessReturnOverRFR[i] * ProductGrossExcessReturnOverRFR[i];      
      }
  
      return slope = 1 / (((sumxy - sumx * sumy / months) / (sumx2 - sumx * sumx / months)));
  }
  </code></pre>
  
  <p>Test data:<br>
  <code>{1.085231224, 2.335034309, 0.346667278}</code> and<br>
  <code>{3.185231224,3.705034309 , -0.883332722}</code> should have slope of 0.3373 if you calculate in Excel using <code>=SLOPE</code> function. But my code produces 0.47 somehow...</p>