JAVA 获取两条直线的交点

JAVA 获取两条直线的交点

public class PointIntersect {

    public static class Point{
        private double x;
        private double y;

        public Point(double x,double y){
            this.x=x;
            this.y=y;
        }

        public double getX() {
            return x;
        }

        public void setX(double x) {
            this.x = x;
        }

        public double getY() {
            return y;
        }

        public void setY(double y) {
            this.y = y;
        }

       @Override
        public String toString() {
            return "Point{" +
                    "x=" + x +
                    ", y=" + y +
                    '}';
        }
    }

    /**
     * 获取两条直线相交的点
     */
    public static Point getIntersectPoint(Point p1, Point p2, Point p3, Point p4){

        double A1=p1.getY()-p2.getY();
        double B1=p2.getX()-p1.getX();
        double C1=A1*p1.getX()+B1*p1.getY();

        double A2=p3.getY()-p4.getY();
        double B2=p4.getX()-p3.getX();
        double C2=A2*p3.getX()+B2*p3.getY();

        double det_k=A1*B2-A2*B1;

        if(Math.abs(det_k)<0.00001){
            return null;
        }

        double a=B2/det_k;
        double b=-1*B1/det_k;
        double c=-1*A2/det_k;
        double d=A1/det_k;

        double x=a*C1+b*C2;
        double y=c*C1+d*C2;

        return  new Point(x,y);
    }

    public static void main(String[] args) {
        Point p1=new Point(1,1);
        Point p2=new Point(5,5);
        Point p3=new Point(2,1);
        Point p4=new Point(2,5);

        Point point=getIntersectPoint(p1,p2,p3,p4);

        if(point==null){
            System.out.print("未相交");
        }else{
            System.out.print("相交于:"+point.toString());
        }
    }
}

测试结果:

相交于:PointIntersect.Point[x=2.0,y=2.0]

转载出处:https://blog.csdn.net/xiaoxl084520/article/details/107105596/

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值