參考書目:《數(shù)值分析》
y=x*x-a求零點 用零點附近的切線求x軸的交點,在以交點做切線進而不斷迭代來近似拋物線的零點 由于該函數(shù)在零點附近是收斂的(二階收斂)所以能不斷迭代
//main函數(shù)入口
#include <stdio.h>#include <math.h>double sqrt1(double a,int tot);double sqrt2(double a,int tot);double sqrt3(double a,int tot);int main(void){double i;int j;PRintf("input number to be sqrt:/n");scanf("%lf %d",&i,&j);printf("sqrt number is /n%.9f /n%.9f /n%.9f",sqrt1(i,j),sqrt2(i,j),sqrt3(i,1E-10));return 0;}double sqrt1(double a,int tot) //直接傳入迭代次數(shù){double x,y;int i;x=a/2;for(i=0;i<tot;i++){y=(x+a/x)/2;x=y;}return y;}double sqrt2(double a,int tot) #include <stdio.h>#include <math.h>double sqrt1(double a,int tot);double sqrt2(double a,int tot);double sqrt3(double a,int tot);int main(void){ double i; int j; printf("input number to be sqrt:/n"); scanf("%lf %d",&i,&j); printf("sqrt number is /n%.9f /n%.9f /n%.9f",sqrt1(i,j),sqrt2(i,j),sqrt3(i,1E-10)); return 0;}double sqrt1(double a,int tot)//傳入二分迭代次數(shù){ double x,y; int i; x=a/2; for(i=0;i<tot;i++) { y=(x+a/x)/2; x=y; } return y;}double sqrt2(double a,int tot){ int i; double low,mid,high; low=0; high=a>1?a:1; mid=(low+high)/2; for(i=0;mid*mid!=a&&i<tot;i++)//如果直接相等退出循環(huán) { if(mid*mid<a) { low=mid; mid=(low+high)/2; } else { high=mid; mid=(low+high)/2; } } return mid;}double sqrt3(double a,int err){ double x,y,temp; temp=a/2; do{ x=temp; //temp保留中間結(jié)果 方便x,y的比較 temp=(x+a/x)/2; y=temp; }while(fabs(x-y)>err); return y;}測試結(jié)果:二分求根收斂速度遠小于牛頓迭代}
新聞熱點
疑難解答