嘿,我正在尝试编写一个程序来执行牛顿法并找到方程 exp(-x)-(x^2)+3 的根。它的工作原理是找到根,但我也希望它在每次迭代后打印出根,但我无法让它工作,谁能指出我的错误,我认为它与我的索引有关?
太感谢了 :)
#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);
}