首页 > 学院 > 开发设计 > 正文

二分求根及牛顿迭代求根分析

2019-11-08 18:35:41
字体:
来源:转载
供稿:网友

参考书目:《数值分析》 

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;}

测试结果:二分求根收敛速度远小于牛顿迭代}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表