//------------------------------------------------------------------- // rootfind.cpp // // This program illustrates the Newton-Raphson Method by using // it to calculate the twelfth-root of two (a number which has // significance in music theory). // // programmer: ALLAN CRUSE // written on: 07 NOV 2005 //------------------------------------------------------------------- #include // for printf(), perror() #include // for fabs() double f( double x ) { // returns x**12 - 2 double power = 1.0; for (int i = 0; i < 12; i++) power *= x; power -= 2.0; return power; } double g( double x ) { // returns 12 * x**11 double power = 1.0; for (int i = 0; i < 11; i++) power *= x; power *= 12.0; return power; } int main( int argc, char **argv ) { printf( "\nUsing Newton-Raphson Method " ); printf( "to find the twelfth-root of two \n" ); // compute the root of the equation: f(r) = 0 double r0 = 1.0; // initial value double r_next = r0, r_curr = r0; for (int i = 0; i < 20; i++) { r_curr = r_next; printf( "\n\tr%d = %2.5f ", i, r_curr ); r_next = r_curr - f( r_curr )/g( r_curr ); if ( fabs( r_next - r_curr ) < 0.00000000001 ) break; } // check the result double r = 1.0; for (int i = 0; i < 12; i++) r *= r_curr; printf( "\n\nCheck: %2.5f**12 = %2.5f \n\n", r_curr, r ); }