点到直线距离C++源码实现

原理

思路1(如果不记得叉乘公式的话):
利用点乘:
在这里插入图片描述

思路2:
利用叉乘:
在这里插入图片描述

代码实现:

定义Point结构体,Line结构体包含两个点成员,Vec结构体代表向量

#include <string>
#include <math.h>
using namespace std;

struct Vec{
    float x_;
    float y_;
    float z_;
    Vec(){}
    float dot(const Vec& other) const{
        return (x_*other.x_+y_*other.y_+z_*other.z_);
    }
    Vec cross_norm(const Vec& other) const{
        Vec res;
        res.x_ = y_*other.z_-z_*other.y_;
        res.y_ = -(x_*other.z_-z_*other.x_);
        res.z_ = y_*other.x_-x_*other.y_;
        return res;
    }
    float norm()const{
        return sqrt(x_*x_+y_*y_+z_*z_);
    }
};

struct Point{
    float x_;
    float y_;
    float z_;
    Point(float x,float y,float z=0):x_(x),y_(y),z_(z){}
    Vec operator-(const Point& b) const{
        Vec vec;
        vec.x_ = x_-b.x_;
        vec.y_ = y_-b.y_;
        vec.z_ = z_-b.z_;
        return vec;
    }
    float norm()const{
        return sqrt(x_*x_+y_*y_+z_*z_);
    }
};

struct Line{
    Point a_;
    Point b_;
    Line(Point a,Point b): a_(a),b_(b){}
};

float p2l(const Point& c, const Line& l){
    Point a = l.a_;
    Point b = l.b_;
    Vec vec0 = l.b_ - l.a_;
    Vec vec1 = c - l.a_;
    float res = vec0.dot(vec1);
    float cs = res / vec0.norm() / vec1.norm();
    float si = sqrt(1-cs*cs);
    return vec1.norm()*si;
}

float p2l2(const Point& c, const Line& l){
    Point a = l.a_;
    Point b = l.b_;
    Vec vec0 = l.b_ - l.a_;
    Vec vec1 = c - l.a_;
    Vec res = vec0.cross_norm(vec1);
    return res.norm()/vec0.norm();
}

int main(){
    Point A(1.0,1.3,0.5);
    Point B(2.0,1.0);
    Point C(28,1.33,99);
    Line L(A,B);
    float res = p2l(C,L);
    float res2 = p2l2(C,L);

    printf("dis of point to line is %f vs %f",res,res2);

    return 0;
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Attention is all you

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值