牛頓迭代法要計算
(1) y1=f(x) 在 x 的函數(shù)值
(2) d1=f'(x) 在x 的值
你可以寫兩個函數(shù),分別計算y1,d1
如果一階導數(shù)有解析解,則可用賦值語句,否則要寫數(shù)值解子程序。
步驟:
設解的精度,例 float eps=0.000001;
設x初值,x1;
迭代循環(huán)開始
算y1 = f(x1);
算d1 = f'(x1)
用牛頓公式 算出 x2; [x2 = x1 - y1 / d1]
如果 fabs(x2-x1) > eps 則重新迭代 -- 用新的函數(shù)值和一階導數(shù)值推下一個 新x.
牛頓迭代法:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAXREPT 1000
float f(float x)
{return(x*exp(x)-1);
}
float df(float x)
{return((x+1)*exp(x));
}
float iterate(float x)
{float x1;
x1=x-f(x)/df(x);
return(x1);
}
void main()
{
float x0,x1,eps,d;int k=0;
printf("\n please input x0,eps:");
scanf("%f,%f",&x0,&eps);
printf("\n k xk\n");
printf(" %d %f\n",k,x0);
do
{k++;
x1=iterate(x0);
printf(" %d %f\n",k,x1);
d=fabs(x1-x0);
x0=x1;
}
while((d>=eps)&(k<MAXREPT));
if(k<MAXREPT)
printf("the root is x=%f, k=%d\n",x1,k);
else
printf("\n The iteration is failed!\n");
getch();
}
|