I need help finding a root of a function using both the direct search method and then the Newton-Raphson method. I have individual codes for each method, but I don't know how to combine them into one code using a pointer. The function I ultimately need to use is
f(x)= x^3 - 0.2589x^2 + 0.02262x - 0.001122 = 0
Here is my direct search method code.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
double f(double x);
double direct(double a, double b, int n);
int main()
{
double x0 = 12.0, xn = 16.0;
int n = 400;
printf( "The root is %f\n", direct(x0, xn, n) );
return 0;
}
double f(double x)
{
double y;
y = 667.38/x * (1 - exp(-0.146843*x)) - 40.0;
return y;
}
double direct(double a, double b, int n)
{
int i;
double dx, x, f1, f2;
dx = (b - a) / n;
f1 = f(a);
for (i = 1; i <= n; i++) {
x = a + dx * i;
f2 = f(x);
if (f1 * f2 <= 0) break;
f1 = f2;
}
return x - dx/2;
}
Here is my Newton-Raphson method code.
#include <stdio.h>
#include <math.h>
#define EPS0 1.0e-12
double f(double x);
double fp(double x);
double newton_raphson(double x, double eps);
int main()
{
double xi = 0, eps = 1.0e-6;
printf( "The root is %f\n", newton_raphson(xi, eps) );
return 0;
}
double f(double x)
{
double y;
y = 1.5*x / pow((1+x*x), 2) - 0.65 * atan(1/x) + 0.65*x / (1+x*x);
return y;
}
double fp(double x)
{
double y;
y = (2.8 - 3.2*x*x) / pow((1+x*x), 3);
return y;
}
double newton_raphson(double x, double eps)
{
double x1, dx, fx, fpx;
do {
fx = f(x);
fpx = fp(x);
if (fabs(fpx) < EPS0)
{
printf( "Warning: slope --> 0 !!!\n");
break;
}
x1 = x - fx/fpx;
dx = x1 - x;
x = x1;
} while (fabs(dx) > eps || fabs(fx) > EPS0);
return x1;
}
[edit]Code block added - OriginalGriff[/edit]