title: Speed up a C++ code implementing numerical integration
body: <p>I have this C++ code that implements a rectangular numerical integration</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cmath&gt;
  using namespace std;
  
  float pdf(float u){
       return (1/(pow(1+u, 2)));
  }
  
  float cdf(float u){
        return (1 - 1/(u+1));
  }
  // The main function that implements the numerical integration, 
  //and it is a recursive function
  float integ(float h, int k, float du){
        float res = 0;
        if (k == 1){
           res =  cdf(h);
        }else{
           float u = 0;
      while (u &lt; h){
          res += integ(h - u, k - 1, du)*pdf(u)*du;
          u += du;
      }
  }
       return res;
  }
  int main(){
      float du = 0.0001;
      int K = 3;
      float gamma[4] = {0.31622777, 0.79432823, 
                  1.99526231, 5.01187234};
      int G = 50;
      int Q = 2;
      for (int i = 0; i &lt; 4; i++){
          if ((G-Q*(K-1)) &gt; 0){
              float gammath = (gamma[i]/Q)*(G-Q*(K-1));
              cout&lt;&lt;1-integ(gammath, K, du)&lt;&lt; endl;
      }
  
   }
  
      return 0;
  }
  </code></pre>
  
  <p>I am facing a speed problem, although I switched to C++ from Python and MATLAB, because C++ is faster. The problem is that I need a small step size <em>du</em> to get an  accurate evaluation of the integration. </p>
  
  <p>Basically, I want to evaluate the integral at 4 different points defined by gammath, which is a function of other defined parameters. </p>
  
  <p>Is there anyway I can speed up this program? I already have 25x+ speed factor over the same code in Python, but still the code takes too long (I ran it all night, and it wasn't finished in the morning). And this is only for K=3, and G=50. In other cases I want to test K = 10, and G = 100 or 300.</p>
  
  <p>Thanks in advance for any tips.</p>