利用公式近似计算log2(x)

公式详见程序设计基础(清华大学出版社)P102
解题时,注意应向log2函数传递的参数的选取及其类型即可
代码如下:

#include 
#include 
using namespace std;
const double q = 1e-6;
double s[100000], a[100000], b[100000];

int main()
{
	b[0] = 1;
	s[0] = 0;
	double x;
	int i, n;
	for (i = 0; i < 100000; i++) // define b[i]
		b[i] = pow(0.5, i);
	for (i = 1; ; i++) // define n
	{
		if (pow(0.5, i) <= q)
			break;
	}
	n = i;
	while (cin >> x && x)
	{
		cout << log2(x) << endl;
	}
	return 0;
}


double log2(double x, int n)
{
	b[0] = 1;
	s[0] = 0;
	int i;
	for (i = 0; i < 100000; i++) // define b[i]
		b[i] = pow(0.5, i);
	a[0] = x;
	for (i = 1; i <= n; i++)  // define a[i]
	{
		if (a[i - 1] * a[i - 1] < 2)
			a[i] = a[i - 1] * a[i - 1];
		else
			a[i] = a[i - 1] * a[i -  1] / 2.0;
	}
	for (i = 1; i <= n; i++)
	{
		if (a[i - 1] * a[i - 1] < 2)
			s[i] = s[i - 1];
		else
			s[i] = s[i - 1] + b[i];
	}
	if (x > 0 && x < 1)
		cout <<  -log2(1/x) << endl;
	else if (x > pow (2.0, n))
		cout <<  n + log2(x / pow(2.0, n)) << endl;
    else
		cout << s[n] << endl;
}


你可能感兴趣的:(利用公式近似计算log2(x))