我怎么才能写一个函数把pi (π)返回给给定的小数位数呢?
速度不是问题。我一直在看http://bellard.org/pi/,但我仍然不明白如何获得pi的第n位。
发布于 2010-04-16 17:00:00
在微积分中有一种叫做泰勒级数的东西,它提供了一种简单的方法来计算任意精度的许多无理性值。
Pi/4 =1- 1/3 + 1/5 - 1/7 + ...
(来自http://www.math.hmc.edu/funfacts/ffiles/30001.1-3.shtml )
继续添加这些项,直到您希望的精度位数稳定下来。
泰勒定理是一个强大的工具,但使用该定理推导这个级数超出了问题的范围。这是大学一年级的标准微积分,如果你对更多细节感兴趣,可以很容易地用谷歌搜索。
我并不是说这是计算圆周率最实用的方法。这取决于你为什么真的需要这么做。出于实际目的,您只需从众多已发布的版本中复制所需数量的数字即可。我建议这是一个简单的介绍如何将无理性值等同于无穷级数。
发布于 2010-04-16 18:32:21
试试"Computation of the n'th digit of pi in any base in O(n^2)“。它可能是已知的最快的算法,它不需要任意(读取大量)精度的浮点数,并且可以直接以10为基数(或任何其他)给出结果。
发布于 2010-04-16 19:01:02
作为JeffH存储每个变体的方法的替代方法,您可以只存储最大位数,并删除不需要的位数:
#include <string>
#include <iostream>
using std::cout; using std::endl; using std::string;
// The first 99 decimal digits taken from:
// http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
// Add more as needed.
const string pi =
"1415926535"
"8979323846"
"2643383279"
"5028841971"
"6939937510"
"5820974944"
"5923078164"
"0628620899"
"8628034825"
"342117067";
// A function in C++ that returns pi to X places
string CalcPi(const size_t decimalDigitsCount)
{
string returnValue = "3";
if (decimalDigitsCount > 0)
{
returnValue += "." + pi.substr(0, decimalDigitsCount);
}
return returnValue;
}
int main()
{
// Loop through all the values of "pi at x digits" that we have.
for (size_t i = 0; i <= pi.size(); ++i)
{
cout << "pi(" << i << "): " << CalcPi(i) << endl;
}
}
https://stackoverflow.com/questions/2654749
复制