/* gradient descent examples */ 
#include (stdio.h)

float lambda=0.25, epsilon=0.001, x=0.1, y ;
int   iter=0 ;

float f(float x) {
  return (x-1)*(x-1) ;
  /* return x*x * (x*x - 2) + 1 ; */
}
float derivative(float x) {
  return 2 * (x-1) ;
  /* return 4*x * (x-1) ; */
}

void main(void) {
  do {
       iter++ ;
       y = f(x) ;
       printf ( "%5d x=%6.3f y=%6.3f\n", iter, x, y ) ;
       x -= lambda * derivative(x) ;
  } while (y > epsilon) ;
}



Back to lecture