我在程序中使用不定的一系列项来计算 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/