/******** * zeros * * finds the zero of a function * by bisecting the range where * the zero is to be found on * each iteration. * * compile with "cc -lm zeros.c -o zeros" * * - Jim Mahoney, Sep 2001 ***********/ #include #include /**************************************************** /* Here's the function that we'll find the zero of. */ double f(double x, double B) { return( sin(x) - B*x*x ); } /* and its derivative */ double dfdx(double x, double B) { return( cos(x) - 2.0*B*x ); } /* and a way to print it out for the user to see. */ void print_f(){ printf(" sin(x) - B*x*x " ); } /************************************************* /* Find the value of x1< x < x2 where f(x,B) = 0 */ /* using a bisection algorithm, continuing until the */ /* error in x stops decreasing or we hit the iteration limit. */ double bisection( double B, double x1, double x2) { double f1,f2,dx,dxLast,xmid,fmid; int iterationMax = 100; int i=0; f1 = f(x1,B); f2 = f(x2,B); if ( f1*f2 > 0.0 ) { /* -- Consistency checks -- */ printf(" ** ERROR in bisection ** \n"); printf(" f(xMin,B) and f(xMax,B) have the same sign. \n"); exit(); } dx = fabs(x1-x2); dxLast = 2.0*dx; while ( (dx < dxLast) && (i 0) { x1 = xmid; f1 = fmid; } else { x2 = xmid; f2 = fmid; } dx = fabs(x1-x2); } return( (x1+x2)/2.0 ); } /************************************************* /* Find the zero of f(x,B) using its first derivative dfdx /* and a starting point x0 , continuing until the */ /* error in x stops decreasing or we hit the iteration limit. */ double newtons( double B, double x0) { double fx0, deriv, dx, dxLast, xNew; int iterationMax = 100; int i=0; dx = 1e20; /* first step should be smaller than this */ dxLast = 2e20; /* which should be smaller than this */ while ( (dx < dxLast) && (i