So I'm working on a project.... Completely lost as to how to combine all of these things. (It seems totally unnecessary, but all steps are required.) Many of these weren't really explained in great detail by the professor.
The following function contains a real root between 0 and 3:
a) Plot f(x) versus x on a graph using any plot programs you know of
b) Using an increment of 0.25 and the direct research method, determine the intervals within which the root occurs
c) Within each of the intervals, determine the root using the Newton-Raphson method within the precision of 0.001.
Requirement: you need to write a C-code that combines the direct search method with the Newton-Raphson method to achieve the above objective.
Your C-code must contain the following features: (1) use of arrays, (2) use of pointers, (3) use of structure, (4) use of union, (5) use of functions and function calls, (6) formatted output on screen and (7) saving of the same output on a file.
Totally know this is wrong, but any help would be greatly appreciated. Here's what I have so far:
#include <stdio.h>
#include <math.h>
#define EPS0 1.0e-3
double f(double x);
double fp(double x);
double direct(double a, double b, int n);
double newton_raphson(double x, double eps);
union number {
int x;
double y;
};
int main ()
{
double x0 = 0, xn = 3;
int n = 0.25;
printf( "The root is %f\n", direct(x0, xn, n) );
return 0;
}
double f(double x)
{
double y;
y = (x*x*x) - (.2589*x*x) + (.02262*x) - 0.00112;
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;
}
{
double xi = 0, eps = 1.0e-12;
printf( "The root is %f\n", newton_raphson(xi, eps) );
return 0;
}
double f(double x)
{
double y;
y = (x*x*x) - (.2589*x*x) + (.02262*x) - 0.00112;
return y;
}
double fp(double x)
{
double y;
y = (3*x*x) - (.5178*x) + .02262;
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;
}