数值算法(《编程珠玑(续)》第14章课后题)

第14题:在我的电脑上能够运行,因为double是有精度限制的,当A=103时,运行10次就会停止了。

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main()
{
	double A=103;
	double x=1.0;
	double newx=0;
	int i=0;
	while(1)
	{
		cout<<++i<<endl;
		newx=0.5*(x+A/x);
		if(newx==x)
		{
			cout<<x<<endl;
			break;
		}
		x=newx;
	}

	system("pause");
	return 0;
}
第17题:

看到结果我是彻底给跪了,我还以为程序写错了,然后把两个结果比较了一下,就是那个0.0000001的门限,结果是没有错误。不知道C++里是怎么写的sprt,根本不像是《编程珠玑》里写的,库函数已经特别快了,或许是因为《编程珠玑》毕竟是在上世纪80年代写的书,库函数已经被优化了30多年了吧。如下是代码和结果:

#include<iostream>
#include<ctime>
using namespace std;

double distanceEuclid(double p,double q)
{
	p=abs(p);
	q=abs(q);
	if(p<q)
		swap(p,q);
	if(p==0.0)
		return q;
	int n=3;
	double r;
	while(n--)
	{
		r=q/p;
		r=r*r;
		r=r/(4+r);
		p=p+2*r*p;
		q=q*r;
	}
	return p;
}

int main()
{
	const int N=10000000;
	int *A=new int[N];
	clock_t start,end;
	
	srand(12345);
	start=clock();
	for(int i=0;i<N;i++)
	{
		double a=rand();
		double b=rand();
		A[i]=distanceEuclid(a,b);
	}
	end=clock();
	cout<<end-start<<endl;

	srand(12345);
	start=clock();
	for(int i=0;i<N;i++)
	{
		double a=rand();
		double b=rand();
		if(A[i]-sqrt(a*a+b*b)>0.0000001)
			cout<<"error"<<endl;
	}
	end=clock();
	cout<<end-start<<endl;

	system("pause");
	return 0;
}
结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值