Hey I'm trying to write a program to carry out newtons method and find the roots of the equation exp(-x)-(x^2)+3. It works in so far as finding the root, but I also want it to print out the root after each iteration but I can't get it to work, Could anyone point out my mistake I think its something to do with my indexing?
Thanks a million :)
#include <stdio.h>
#include <math.h>
#include <malloc.h>
//Define Functions:
double evalf(double x)
{
double answer=exp(-x)-(x*x)+3;
return(answer);
}
double evalfprime(double x)
{
double answer=-exp(-x)-2*x;
return(answer);
}
double *newton(double initialrt,double accuracy,double *data)
{
double root[102];
data=root;
int maxit = 0;
root[0] = initialrt;
for (int i=1;i<102;i++)
{
*(data+i)=*(data+i-1)-evalf(*(data+i-1))/evalfprime(*(data+i-1));
if(fabs(*(data+i)-*(data+i-1))<accuracy)
{
maxit=i;
break;
}
maxit=i;
}
if((maxit+1==102)&&(fabs(*(data+maxit)-*(data+maxit-1))>accuracy))
{
printf("\nMax iteration reached, method terminated");
}
else
{
printf("\nMethod successful");
printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1,*(data+maxit));
}
return(data);
}
int main()
{
double root,accuracy;
double *data=(double*)malloc(sizeof(double)*102);
printf("NEWTONS METHOD PROGRAMME:\nEquation: f(x)=exp(-x)-x^2+3=0\nMax No iterations=100\n\nEnter initial root estimate\n>> ");
scanf("%lf",&root);
_flushall();
printf("\nEnter accuracy required:\n>>");
scanf("%lf",&accuracy);
*data= *newton(root,accuracy,data);
printf("Iteration Root Error\n ");
printf("%d %lf \n", 0,*(data));
for(int i=1;i<102;i++)
{
printf("%d %5.5lf %5.5lf\n", i,*(data+i),*(data+i)-*(data+i-1));
if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0)
{
break;
}
}
getchar();
getchar();
free(data);
return(0);
}