
Untitled
By: a guest on
May 26th, 2012 | syntax:
None | size: 1.87 KB | hits: 10 | expires: Never
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* function prototypes */
double func1(double x);
double func1_d(double x);
double Newton_Raphson(double x0);
int main(int argv, char *argc[])
{
double x, x_old, f_x_old;
printf("\nHomework 6:\n\n x f(x) sign change\n-----------------------------------------\n");
for(x=-1.0;x<=5.0;x+=.25) {
if((func1(x) < 2.0093) && (func1(x) > -1.9593)) {
printf("%8.2f %12.4f Y\n", x, func1(x));
printf(" A refined root is %12.6e\n", Newton_Raphson((double)(x+x_old)/2));
continue;
}
printf("%8.2f %12.4f\n", x, func1(x));
x_old = x;
f_x_old = func1(x);
}
return (EXIT_SUCCESS);
//exit(0);/* normal termination */
}
double func1(double x)
{
return (x*x*x)-(x*x)+(-9.0*x)+8.9;
}
double func1_d(double x)
{
return (3.0*x*x)+(-2.0*x)-9.0;
}
double Newton_Raphson(double x0)
{/* YOU ARE NOT ALLOWED TO MODIFY THIS FUNCTION */
/* the Newton-Raphson method is used to find a root of f(x) for a given
initial guess x0 */
/* double func1(double x) computes f(x) while double func1_d(double x)
computes f'(x) */
int debug = 1;
double tolx, tolf, x1, del_x;
double f0, f1, f_d0;
f0 = func1(x0);
if(debug != 0) printf(" f(%g) = %e \n", x0, f0);
/* define tolerances */
tolx = 1.e-8 * fabs(x0); /* tolerance for |x1 - x0| */
tolf = 1.e-6 * fabs(f0); /* tolerance for |f(x1)| */
do{
f_d0 = func1_d(x0);
x1 = x0 - f0/f_d0;
f1 = func1(x1);
if(debug != 0) printf(" f(%g) = %e\n", x1, f1);
del_x = fabs(x1 - x0);
/* update x0 and f0 for the next iteration */
x0 = x1;
f0 = f1;
} while(del_x > tolx && fabs(f1) > tolf);
return x1;
}