如何在C中获得最小的精度

时间:2015-03-28 14:16:45

标签: c pi

我正在使用一系列不确定的术语来计算我的程序中的Pi。当我显示结果计算时,Pi的整体精度不是我想要的。我相信转换规范或我使用的原始类型存在问题。

这是我得到的:

Pi:3.141594

这就是我想要的:

Pi:3.14159265358979323846

以下是我的Pi计算方法中的一些代码:

 //Global variables

 // Variables to hold the number of threads and the number of terms 
 long numOfThreads, numOfTerms;
 // Variable to store the pieces of Pi as it is being calculated by each thread
 double piTotal = 0.0;





// Use an indefinite series of terms to calulate Pi   
 void calculatePi(){
      // Variable to store the sign of each term
      double signOfTerm = 0.0;
      // Variable to to be the index of the loop variable
      long k;
 #pragma omp parallel for num_threads(numOfThreads) \
 default(none) reduction(+: piTotal) private(k, signOfTerm)\
 shared(numOfTerms)

     for (k = 0; k <= numOfTerms; k++) {
        if (k == 0) {
        signOfTerm = 1.0;
        }
     // Sign of term is even
        else if (k % 2 == 0) {
        signOfTerm = 1.0;
        }
    // Sign of term is odd
        else if (k % 2 == 1) {
        signOfTerm = -1.0;
      }
    // Computing pi using an indefinite series of terms
        piTotal += (signOfTerm) * 4 / (2 * k + 1);
        }
      }

  // Print the result
 void printResult(){
      printf("\n" "Calulation of Pi using %d " "terms: %f",numOfTerms,piTotal);
      }                              

2 个答案:

答案 0 :(得分:0)

以下是我为解决问题所做的工作。我不得不将转换规范从%f更改为%.17g。这给了我比浮动的默认打印值更精确。

&#13;
&#13;
 // Print the result
 void printResult(){
      //Returning the result up to 17 places after the decimal removing trailing zeros 
      printf("\n" "The value of Pi using %d term(s): %.17g", numOfTerms, piTotal);
      }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请注意,(k%2 == 0)将处理k == 0的情况,因此您不需要对k == 0进行特殊检查。此外,该系列收敛速度非常慢,它是&#39;以下是pi的简单公式列表中的第一个:

pi / 4 = arctan(1)

pi / 4 = arctan(1/2)+ arctan(1/3)

pi / 4 = 4 * arctan(1/5) - arctan(1/239)

pi / 4 = 6 * arctan(1/8)+ 2 * arctan(1/57)+ arctan(1/239)