1. 程式人生 > >由任意3點計算得出圓心座標,考慮斜率不存在的情況

由任意3點計算得出圓心座標,考慮斜率不存在的情況

下面給出由三角計算圓心座標的程式碼

思路:根據任意兩點的垂直平分線角方程,考慮斜率不存在的情況。

/************************************************************************/
/*由三點計算圓心座標                                                     */
/************************************************************************/
bool CntCalBy3Pts(const double x1, const double y1,
		  const double x2, const double y2,
		  const double x3, const double y3,
		  double& cnt_x,   double& cnt_y)
	{
	//step1:計算中點座標
	double mid_x12 = (x1 + x2)/2;
	double mid_y12 = (y1 + y2)/2;
	double mid_x23 = (x2 + x3)/2;
	double mid_y23 = (x2 + x3)/2;
	//step2:計算垂直平方線斜率
	double k1 = 0, k2 = 0;
	//case1:pt1,pt2組成線段斜率不存在
	if (!(y1 - y2))
		{
		cnt_x = mid_x12;
		k2 = -((x2 - x3)/(y2 - y3));
		cnt_y = k2 * mid_x12 + mid_y23 - k2 * mid_x23;
		return true;
		}
	//case2:pt2,pt3組成的線段斜率不存在
	else if (!(y2 - y3))
		{
		cnt_x = mid_x23;
		k1 = -((x1 - x2)/(y1 - y2));
		cnt_y = k1 * mid_x23 + mid_y12 - k1 * mid_x12;
		return true;
		}
	//case3:兩條線段斜率均存在
	else
		{
		k1 = -((x1 - x2)/(y1 - y2));
		k2 = -((x2 - x3)/(y2 - y3));
		if (k1 == k2)
			{
			return false;
			}
		double b1 = mid_y12 - k1 * mid_x12;
		double b2 = mid_y23 - k2 * mid_x23;
		cnt_x = (b2 - b1)/(k1 - k2);
		cnt_y = k1 * cnt_x + b1;
		return true;
		}
	}