二分法求派Pi

二分法求派,因为可以有二分法求sin值,我们可以借助三角形面积公式 S = 1/2sinα,求圆的内接正多边形的面积来近似代替圆面积,比如

​ 当边长为1的圆内接正四边形时,相当于四个等腰三角形面积之和 为 2,代替圆面积,由于圆面积S = Pi * R * R 求得Pi为2,如此我将圆内接四百万边形就非常接近真实的Pi值了

#include 
#include 
using namespace std;

struct node{
	double x,y;
	double jiao;
};

node l,r,mid;

double j,k;

int main()
{
	l.x = 0;
	l.y = 1;
	l.jiao = 90;
	
	r.x = 1;
	r.y = 0;
	r.jiao = 0;
	
	double s = 0,pi0 = 100,pi1 = 0;
	double avg;
	
	cout << "avg = ";
	cin >> avg;
	j = (double)360/avg;
	/////////////////////////////////
	while(l.jiao-r.jiao>1e-7)//LR两夹角之间的角度没达到10的负7次方,
	{//即精度不足小数点后7位就进行二分
		mid.x = (l.x+r.x)/2;//取两点中点
		mid.y = (l.y+r.y)/2;
		
		k = 1/sqrt(mid.x*mid.x+mid.y*mid.y); 
		
		mid.x *=k;//中点与圆点的射线在圆上的交点坐标(mid.x,mid.y)
		mid.y *=k;
		
		mid.jiao = (l.jiao+r.jiao)/2;//该射线夹角为(L+R)/2
		
		if(j<mid.jiao) l = mid;//若mid角大于j则在下半部分查找
		else r = mid;	//反之在上半部分查找
	}
//	cout << mid.y/1;
	////////////////////////////////////
	s = avg * 1 * 1 * 0.5 *mid.y;//sin(j);	
	
	double pi = s;
	
	cout <<"Pi = " << pi;
} 

输出值

avg = 4
Pi = 2
--------------------------------
Process exited after 3.647 seconds with return value 0
请按任意键继续. . .

avg = 40
Pi = 3.12869
--------------------------------
Process exited after 2.3 seconds with return value 0
请按任意键继续. . .

avg = 4000000
Pi = 3.14159
--------------------------------
Process exited after 3.612 seconds with return value 0
请按任意键继续. . .

你可能感兴趣的:(数据结构与算法原理,c++)