●割圓法
????????一個(gè)圓如下面左圖所示,其半徑為1,其內(nèi)部?jī)?nèi)接一個(gè)正六邊形。設(shè)正六邊形的邊長(zhǎng)為y1。由幾何知識(shí)可得知y1=1,所以圓的周長(zhǎng)可近似為正六邊形的周長(zhǎng)C=6×y1=6.所以圓周率為前面的近似圓周長(zhǎng)與圓直徑之比,即C/2= 3≈π,這就是按照割圓法來(lái)得到圓周率近似值的方法。
分析:(上面右圖所示)
其中邊長(zhǎng)為m、y1、y2的三條邊構(gòu)成一個(gè)小直角三角形,根據(jù)勾股定理可得:
?其中邊長(zhǎng)為n,y1,1的三條邊構(gòu)成一個(gè)較大的三角形,根據(jù)勾股定理可得:
結(jié)合條件圖中已知條件(m+n=1)和幾何關(guān)系對(duì)公式繼續(xù)進(jìn)行化簡(jiǎn)推導(dǎo):
所以圓周率π的近似值為:
如果內(nèi)接24邊形,其邊長(zhǎng)為y3,則其圓周率為:?
?如果內(nèi)接48邊形,其邊長(zhǎng)為y4,則其圓周率為:
?……?
綜上歸納可知,在割圓術(shù)這個(gè)算法中主要用到以下兩個(gè)公式:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class cyclotomic {
public:
void cyclotomic1()
{
int i = 1,a=1;
double len = 1;
while(i<=n)
{
len = 2 - sqrt(4 - len); //內(nèi)接多邊形的邊長(zhǎng)
a *= 2;
i++;
}
pi = 3.0 * (double)a * sqrt(len);
}
void showresult()
{
cout.precision(12); //小數(shù)點(diǎn)后第十二位
cout << pi << endl;
}
int n;
double pi;
};
void text()
{
cyclotomic c;
cout << "輸入要切割的次數(shù):" << endl;
cin>>c.n;
c.cyclotomic1();
c.showresult();
}
int main()
{
text();
}
●級(jí)數(shù)公式法
????????在微積分中,對(duì)一個(gè)表達(dá)式進(jìn)行級(jí)數(shù)展開(kāi)并取極限便可以得到一系列的迭代計(jì)算公式。對(duì)于圓周率π也可以采用相同的方法來(lái)得到級(jí)數(shù)公式(泰勒展開(kāi)式)。這樣的級(jí)數(shù)公式很多,依賴于不同的級(jí)數(shù)展開(kāi)表達(dá)式,下面就是一個(gè)典型的求圓周率級(jí)數(shù)公式的例子:
#include<iostream>
#include<iomanip>
using namespace std;
class series1 {
public:
void series_1()
{
int i = 1;
double sum=1,record=1, m=1, n=3,t;
while (i <= x)
{
t = m / n;
t = t * record;
sum += t;
m += 1;
n += 2;
record = t;
i++;
}
pi = 2.0 * sum;
}
void showresult()
{
cout.precision(12);//小數(shù)點(diǎn)后第十二位
cout << pi << endl;
}
int x;
double pi;
};
void text()
{
series1 s1;
cout << "請(qǐng)輸入該公式往后計(jì)算的位數(shù):" << endl;
cin >> s1.x;
s1.series_1();
s1.showresult();
}
int main()
{
text();
}
●格雷戈里公式法
? ? ? ? 格雷戈里公式的實(shí)質(zhì)是反正切函數(shù)的泰勒展開(kāi)式,屬于級(jí)數(shù)公式的一種,具體公式如下:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Gregory {
public:
void Gregory1()
{
int sign = 1;
double m = 1, term = 1;
while (fabs(term) >= x)
{
pi += term;
m += 2;
sign = -sign;
term = sign / m;
}
pi = 4.0 * pi;
}
void showresult()
{
cout.precision(12);//小數(shù)點(diǎn)后第十二位
cout << pi << endl;
}
double x;
double pi=0;
};
void text()
{
Gregory g;
cout << "輸入精度e的值:" <<endl;
cin >> g.x;
g.Gregory1();
g.showresult();
}
int main()
{
text();
}
●蒙特卡洛
????????在概率算法的文章中,舉的蒙特卡洛算法例子就是用概率的方法去尋找π,具體在http://t.csdn.cn/VifFM文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-449716.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-449716.html
到了這里,關(guān)于【基礎(chǔ)算法】圓周率的多種方法求算 & C++實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!