jma*_*erx 34 algorithm math pi
如何编写一个将pi(π)返回给定小数位数的函数?
速度不是问题.我一直在看http://bellard.org/pi/,但我仍然不明白如何获得pi的第n位数.
Ala*_*lan 30
在微积分中有一个名为泰勒级数的东西,它提供了一种简单的方法来计算许多无理值到任意精度.
Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
(来自http://www.math.hmc.edu/funfacts/ffiles/30001.1-3.shtml)
继续添加这些术语,直到您想要稳定的精度数位.
泰勒定理是一个强大的工具,但使用该定理推导出这一系列超出了问题的范围.这是标准的一年级大学微积分,如果您对更多细节感兴趣,可以轻松转换.
我并不是说暗示这是计算pi的最实用的方法.这取决于你真正需要这样做的原因.出于实际目的,您应该从许多已发布版本中的一个中复制所需数量的数字.我建议将其简单地介绍非理性值如何等同于无限级数.
作为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;
}
}
Run Code Online (Sandbox Code Playgroud)
“ ?在MANDELBROT集合中 ”探讨了复杂平面上的点序列与如何计算其“ Mandelbrot数”(由于缺少更好的术语……确定序列中的点所需的迭代次数)之间的奇怪关系。不是Mandelbrot集的成员)与PI有关。
实际的?可能不会。
意外和有趣?我认同。