Answer

We initialize sum with half of the value of the integrand at the left endpoint of the interval. We must also remember to add in the value of the integrand at the right endpoint when we're done with the loop.

float trapezoid (float a, float b, int N) {

  float sum, h;
  int i;

  sum = integrand(a)/2;
  h = (b-a) / N;
  i = 1;

  while (i < N) {
    sum = sum + integrand(a + i*h);
    i = i + 1;
  }

  sum = sum + integrand(b)/2;
  return(sum*h);

}

Return to lesson.



Christopher R. Johnson
Hamlet Project
Department of Computer Science
University of Utah