Newton's Method



/* Newton's method */

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

#define epsilon 0.0000001

/* function */

double f(double x) {
      return(x*x - 3);
}

/* derivative of f */

double df(double x) {
      return(2*x);
}

int main() {

   double x, oldx;

   printf("Give an initial estimate of zero > ");
   scanf("%lf",&x);
          
   do {
      oldx = x;
      x = x - f(x)/df(x);
      printf("%f\n",x);
   } while (fabs(x-oldx) > epsilon);

   printf("A zero is equal to: %lf", x);
}


Numerical Integration


Riemann sums


/* riemann.c */

#include <stdio.h>

double f( double x) {

  return(x*x) ;
}

int main() {

  double a, b, delta, integral;
  int i,n;

  a = 0;
  b = 1;
  n = 100000;

  delta = (b-a)/n;
  integral = 0.0;

  for (i=0; i < n; i=i+1)
    integral = integral + f(a + i*delta)*delta;

  printf("The integral of f from %f to %f is equal to %f\n",a,b,integral);
}   



/* riemann1.c */

#include <stdio.h>

double f( double x) {

  return(x*x) ;
}

int main() {

  double a, b, delta, integral;
  int i,n;

  a = 0;
  b = 1;
  n = 100000;

  delta = (b-a)/n;
  integral = 0.0;

  for (i=0; i < n; i=i+1)
    integral = integral + f(a + (i+1)*delta)*delta;

  printf("The integral of f from %f to %f is equal to %f\n",a,b,integral);
}