计算3D中线和点之间的角度

Calculating angle between a line and a point in 3D

我正在用 c++ 解决一个问题,我需要确定在 3d 中表示为 2 个点(等等,x.y.z 坐标)的线与断开点之间的角度。下面是一些图片,可能更容易理解。

This is in 2D to display it easier

所以我需要帮助的是找到这个角度

With angle

我已经搜索了几个小时来解决这个问题,我怀疑我只是错过了一些明显的东西。但如果有人能帮助我,我将非常感激:)

使用Law of Cosines:

gamma = acos((asq + bsq - csq) / 2 / sqrt(asq*bsq))

其中 asqbsq 是顶点与其他两点之间的平方距离,csq 是这两点之间的平方距离。

(取自Wikipedia

你有 2 个向量,第一个与 3D 中的线相关,另一个向量连接线的端点和 3D 中的一个点。

要计算 2 个向量之间的角度 theta,您可以利用 V1.V2 = |V1| x |V2| x consine(theta)

这是我从 here 复制的代码片段,用于计算点积。

#include<numeric>    

int main() { 
    double V1[] = {1, 2, 3}; // vector direction i.e. point P2 - point P1
    double V2[] = {4, 5, 6}; // vector direction i.e. point P3 - point P2

    std::cout << "The scalar product is: " 
              << std::inner_product(begin(V1), end(V1), begin(V2), 0.0);

    // TODO: Get theta

    return 0;
}

获得点积后,将其除以 2 个向量的大小,然后取反余弦值得到 theta。

假设你有 A(x1,y1,z1) B(x2,y2,z2) C(x3 ,y3,z3) 并且公共点是 B。所以直线 AB 的方程变为:(x<sub>1</sub>-x<sub>2</sub>)i + (y<sub>1</sub>-y<sub>2</sub>)j + (z<sub>1</sub>-z<sub>2</sub>)k BC 是: (x<sub>2</sub>-x<sub>3</sub>)i + (y<sub>2</sub>-y <sub>3</sub>)j + (z<sub>2</sub>-z<sub>3</sub>)k

余弦 theta = (AB.BC)/(|AB|*|BC|)

这是代码

#include<iostream>
#include<math.h>
#define PI 3.14159265
using namespace std; 
int main()
{
    int x1,x2,x3,y1,y2,y3,z1,z2,z3;
    cout<<"for the first\n";
    cin>>x1>>y1>>z1;
    cout<<"\nfor the second\n";
    cin>>x2>>y2>>z2;
    cout<<"\nfor the third\n";
    cin>>x3>>y3>>z3;
    float dot_product = (x1-x2)*(x2-x3) + (y1-y2)*(y2-y3)+ (z1-z2)*(z2-z3);
    float mod_denom1 = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2));
    float mod_denom2 = sqrt((x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) + (z2-z3)*(z2-z3));
    float cosnum = (dot_product/((mod_denom1)*(mod_denom2)));
    float cos = acos(cosnum)*180/PI;
    cout<< cos;
}