c - 如何在C中获得最大的小数精度

标签 c pi

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

这是我得到的:

圆周率:3.141594

这是我想要的:

圆周率: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);
      }                              

最佳答案

这是我为解决问题所做的事情。我必须将转换规范从 %f 更改为 %.17g。这给了我比 float 的默认打印值更高的精度。

 // 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);
      }

关于c - 如何在C中获得最大的小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29318157/

相关文章:

c - tictactoe 函数不接受输入值

c - 如何编写vb.net代码来编译和执行C程序?

c - 文件中未定义的第一个引用符号

c - 将方法调用放在 for 循环中被认为是不好的做法吗?

c - GCC警告没有强制转换,而MSVC警告有强制转换,为什么?

algorithm - 如何确定我的圆周率计算是否准确?

java - 布冯针(Java实现)

c++ - 使用 long double 还是仅使用 double 来计算 pi?

c - C 中 pi 的无限级数逼近不终止

java - 即使使用 MathContext 也会出现非终止十进制错误