u013052928 于 2016.04.15 22:41 提问

`````` #include <stdio.h>
#include <math.h>
#define PI 3.1415926535898

long double c_K(int k){
if (k == 0){
return (float)1;
}
else  {
long double num=0.0;
for(int m=0;m<k;m++){
num += ((c_K(m)*c_K(k-1-m))/((m+1)*(2*m+1)));}
return num;
}
}

long double e_F(int n){
long double num=0.0;
for(int k=0;k<n;k++){
num += (c_K(k)*(pow((PI*n/2),(2*k+1))/(2*k+1)));
}
return num;
}

int main(){
long double erf_D=e_F(100);
printf("erf_D=%f\n",erf_D);
return 0;
}
``````

2个回答

boostc   2016.04.15 23:11

boostc 回复太阳__sun: 第一次贴代码，贴乱了，:)

u013052928 3Q，还贴代码真贴心

boostc   2016.04.16 00:53

#include
#include
#define PI 3.1415926

int count = 0; //calculate times of funC
double funCMemo[128]; //memo for funC, funCMemo[k] is funC[k] if funCMemoFlag is set
int funCMemoFlag[128]; //memoFlag, 1 is set, 0 is unset

/**
*@brief calculate Ck
*/
double funC(int k){
//printf("funC(%d)\n", k);
if(k != 0){
double sum = 0.0;
int i;
//at first, look up, success
if(funCMemoFlag[k] == 1){
return funCMemo[k];
}
//else
++count;
for(i = 0; i < k; ++i){
sum += ((funC(i) * funC(k - 1 - i)) / ((i + 1) * (2 * i + 1)));
}
//record to memo
funCMemoFlag[k] = 1;
funCMemo[k]=sum;
return sum;
}else{
return 1.0;
}
}

/**
*@brief calculate eK
*/
double funE(int n, int k){
double sum = 0.0;
int i;
for(i = 0; i < k; ++i){
sum += (funC(i) * (pow((pow(PI, 0.5) * n / 2), (2 * i + 1)))/ (2 * i + 1));
}
return sum;
}

int main(){

``````double erf = 0;
int i;
int n,k;
//init funCMemo and funCMemoFlag
for(i = 0; i < 128; ++i){
funCMemo[i]=0.0;
funCMemoFlag[i]=0;
}

printf("input n:\n");
scanf("%d", &n);
printf("input k(<128):\n");
scanf("%d", &k);

//erf = funC(k);
erf = funE(n, k);
printf("erf=%f\n", erf);
printf("count=%d\n", count);
return 0;
``````

}

1.添加了记录数组，极大减少了计算次数；
2.修改了e_F函数中的公式，以及参数(n--x, k ---k);