From: Craig Schroeder [schroeder@santel.net]
Sent: Thursday, December 23, 1999 01:59
To: JoshS@santsys.com
Subject: Definite Integration.

/* This program performs definite integration.  It integrates
a given function, f(x), on the interval [a,b].  N can be set as
a variable to control precision.  The algorithm in use is Simpson's
Rule, and it is VERY fast. */

#include <stdio.h>
#include <math.h>

double f(double x) {return cos(x)+sin(x);}  // function to integrate.

double I(double (*f)(double), double a, double b, unsigned long N)
{
  double w=(b-a)/N, s=0, k=a;
  for(unsigned long i=0; i<N; i++, k+=w)
    s+=f(k)+2*f(k+w/2);
  return (s*2+f(b)-f(a))*w/6;
}

int main()
{
  double a=0, b=3.14159265359;  // integrate on interval [a,b].
  unsigned long N=10000;        // speed vs precision.
  printf("\nf(x) integrated on the interval [%G, %G] is:  %.12G\n\n",
    a, b, I(f, a, b, N));
  return 0;
}
