/*This program finds the root of the equations (x^5)+(x^4)+(x^3)+(x^2)+(x^1)+5=0
and 5(x^2)+2exp(-2x)=0 numerically using the Newton-Raphson method*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
float NRiter(float);
float func(float);
float diff(float);
int c=1, count=0;
int main()
{
float x, r;
printf("For the equation (x^5)+(x^4)+(x^3)+(x^2)+(x^1)+5=0 \n\n");
start:
printf("x0 = ");
scanf("%f", &x);
r = NRiter(x);
if(r==0) printf("This equation does not have a real solution");
else printf("The root is %f\n\n\n", r);
if(c==1)
{
printf("For the equation 5(x^2)+2exp(-2x)=0 \n\n");
c=2;
goto start;
}
getch();
return 0;
}
float NRiter(float x)
{
float t, r, d;
++count;
r = x - func(x)/diff(x);
t = fabs(func(r));
if(count>100) return 0;
if(t<0.001) return r;
else
{
d = NRiter(r);
return d;
}
}
float func(float x)
{
float y;
if(c==1) y = pow(x,5)+pow(x,4)+pow(x,3)+pow(x,2)+pow(x,1)+5;
else y = 5*pow(x,2)+2*exp(-2*x);
return y;
}
float diff(float x)
{
float d;
if(c==1) d = 5*pow(x,4)+4*pow(x,3)+3*pow(x,2)+2*pow(x,1)+1*pow(x,0);
else d = 10*x-4*exp(-2*x);
return d;
}
No comments:
Post a Comment