使用级数 tan{-1}(x) = x – x3/3 + x5/5 – x7/7 + ... 计算 pi 的值。收敛速度有多快? 我的尝试:
/* Calculating the value of pi */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// To calculate tan inverse
float CalculateInverseTan(float fX)
{
float fY = 0;
float fSign = 1;
float fTerm = 0;
int iii = 1;
do
{
float fPow = 1;
int jjj;
// Calculating the power
for (jjj = 1; jjj <= iii; jjj++)
{
fPow *= fX;
}
fTerm = fSign * (fPow / iii);
fY += fTerm;
iii += 2;
fSign *= -1;
} while (fTerm > 0.0001 || fTerm < -0.0001);
return fY;
}
int main()
{
printf("Let x = tan^(-1)(1).\n");
time_t start = time(0);
float fTanInverse1 = CalculateInverseTan(1);
time_t end = time(0);
printf("Therefore x = %f. Time of convergence = %f sec.\nAs x = pi/4, therefore pi = 4x.\nTherefore pi = %f\n", fTanInverse1, difftime(start, end), 4 * fTanInverse1);
return 0;
}
我已经设法计算出 pi 的值。但是收敛时间总是0。
最佳答案
您的程序看起来是否在 <1
秒内完成?
如果是这种情况,您将得到 0
的结果,因为 time
函数的分辨率仅为 1
秒。
您可以改为使用 clock
函数,该函数根据 CPU 的滴答声测量时间,然后您可以将其转换回秒数。
关于计算一个程序所用的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837622/