欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

已知三点求圆心和半径

程序员文章站 2022-05-21 09:25:11
...

https://blog.csdn.net/youhuakongzhi/article/details/86474619

https://blog.csdn.net/qq_43572555/article/details/103470968

很简单的推导,以后用的时候就不用浪费时间了,

圆的一般方程为:

已知三点求圆心和半径

三个已知点为(x1,y1)   (x2,y2)  (x3,y3)

则圆心和半径为:

已知三点求圆心和半径

需要注意,如果三个点共线,那么这三个点肯定无法形成圆,这一问题可通过上式的A来判定,A=0说明三点共线;

 

#include <iostream>
#include <math.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
int main()
{
	//已知三个点确定圆的半径和圆心 
	double x1,x2,x3,y1,y2,y3,x,y,r,A,B,C,D;
	cin>>x1>>y1>>x2>>y2>>x3>>y3;
	A=x1*(y2-y3)-y1*(x2-x3)+x2*y3-x3*y2;
	B=(x1*x1+y1*y1)*(y3-y2)+(x2*x2+y2*y2)*(y1-y3)+(x3*x3+y3*y3)*(y2-y1);
	C=(x1*x1+y1*y1)*(x2-x3)+(x2*x2+y2*y2)*(x3-x1)+(x3*x3+y3*y3)*(x1-x2);
	D=(x1*x1+y1*y1)*(x3*y2-x2*y3)+(x2*x2+y2*y2)*(x1*y3-x3*y1)+(x3*x3+y3*y3)*(x2*y1-x1*y2);
	
	x=-B/(2*A);
	y=-C/(2*A);
	r=sqrt((B*B+C*C-4*A*D)/(4*A*A));
	//-1表示圆不存在 
	if(!A)
        cout<<"-1"<<endl;
	else
	    printf("%.4lf %.4lf %.4lf\n",x,y,r);
	return 0;
}

为加快运算速度,避免重复计算,把上面代码中重复计算的部分,提取出来,对于实时图像计算,分秒必争:

void xxxxx()
{
    float x1,x2,x3,y1,y2,y3,x,y,r,A,B,C,D;

    float x1x1 = x1*x1;
    float y1y1 = y1*y1;
    float x2x2 = x2*x2;
    float y2y2 = y2*y2;
    float x3x3 = x3*x3;
    float y3y3 = y3*y3;

    float x2y3 = x2*y3;
    float x3y2 = x3*y2;

    float x2_x3 = x2-x3;
    float y2_y3 = y2-y3;

    float x1x1py1y1 = x1x1 + y1y1;
    float x2x2py2y2 = x2x2 + y2y2;
    float x3x3py3y3 = x3x3 + y3y3;

    A = x1 * y2_y3 - y1 * x2_x3 + x2y3 - x3y2;
    B = x1x1py1y1 * (-y2_y3) + x2x2py2y2 * (y1-y3) + x3x3py3y3 * (y2-y1);
    C = x1x1py1y1 * x2_x3 + x2x2py2y2 * (x3 - x1) + x3x3py3y3 * (x1-x2);
    D = x1x1py1y1 * (x3y2 - x2y3) + x2x2py2y2 * (x1*y3 - x3*y1) + x3x3py3y3 * (x2*y1-x1*y2);

    x=-B/(2*A);
    y=-C/(2*A);
    r=sqrt((B*B+C*C-4*A*D)/(4*A*A));
    //-1表示圆不存在
    if(!A)
        cout<<"-1"<<endl;
    else
        printf("%.4lf %.4lf %.4lf\n",x,y,r);


}

 

相关标签: 数学基础