我写程序,其实现该配方:如何优化我的程序?
PI = 1/N * SUMM(4 /(1 +((I-0.5)/ N)^ 2)
程序代码:
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
using namespace std;
const long double PI = double(M_PI);
int main(int argc, char* argv[])
{
typedef struct timeval tm;
tm start, end;
int timer = 0;
int n;
if (argc == 2) n = atoi(argv[1]);
else n = 8000;
long double pi1 = 0;
gettimeofday (&start, NULL);
for(int i = 1; i <= n; i++) {
pi1 += 4/(1 + (i-0.5) * (i-0.5)/(n*n));
}
pi1/=n;
gettimeofday (&end, NULL);
timer = (end.tv_usec - start.tv_usec);
long double delta = pi1 - PI;
printf("pi = %.12Lf\n",pi1);
printf("delta = %.12Lf\n", delta);
cout << "time = " << timer << endl;
return 0;
}
如何呈现其最佳的方式的时候会有更少的浮点运算这一部分:
for(int i = 1; i <= n; i++) {
pi1 += 4/(1 + (i-0.5) * (i-0.5)/(n*n));
}
感谢
你是什么意思“少操作” - 一行代码或指令一旦建成? – Nim 2012-03-20 12:52:51
谢尔盖,你的空格键不工作? – jrok 2012-03-20 12:53:23
为什么要结合'printf'和'cout' – triclosan 2012-03-20 12:53:31