参考书目:《数值分析》
y=x*x-a求零点 用零点附近的切线求x轴的交点,在以交点做切线进而不断迭代来近似抛物线的零点 由于该函数在零点附近是收敛的(二阶收敛)所以能不断迭代
//main函数入口
#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) //直接传入迭代次数{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)//传入二分迭代次数{ 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++)//如果直接相等退出循环 { 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保留中间结果 方便x,y的比较 temp=(x+a/x)/2; y=temp; }while(fabs(x-y)>err); return y;}测试结果:二分求根收敛速度远小于牛顿迭代}
新闻热点
疑难解答