Project scenario:
Calculate the angle formed by three-dimensional coordinates
angle between 3D vectors
参考:[三维向量夹角在线计算](https://www.23bei.com/tool/300.html)
Formula:
The formula for calculating the angle between three-dimensional vectors is as follows:
Suppose two three-dimensional vectors are: a=(x1,y1,z1), b=(x2,y2,z2).
The modulus of vector a: |a|=√(x1 2+y1 2+z1^2).
Modulus of vector b: |b|=√(x2 2+y2 2+z2^2).
Dot product of two vectors: a b=(x1x2+y1y2+z1z2).
Let the angle between two vectors be θ, then: cosθ=(x1x2+y1y2+z1z2)/[√(x1 2+y1 2+z1 2)*√(x2 2+y2 2+z2 2)].
The above formulas are all given in three-dimensional coordinates of space. If z=0 in the coordinates, the calculation formula of the plane vector can be obtained.
两个向量夹角θ的取值范围是:[0,π]。当夹角为锐角时,cosθ>0;当夹角为钝角时,cosθ<0。
3D point coordinate class
public class Point {
public float x;
public float y;
public float z;
public Point (float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
}
Calculation formula
/**
* 获取三维向量的夹角.
*
* @param center 夹角中心点
* @param start 起始点
* @param end 结束点
* @return 返回夹角
*/
public static float getTdAngle(Point center, Point start, Point end) {
// 向量1
float x1 = start.x - center.x, y1 = start.y - center.y, z1 = start.z - center.z;
// 向量2
float x2 = end.x - center.x, y2 = end.y - center.y, z2 = end.z - center.z;
System.out.println("x1/y1/z1=" + x1 + "/" + y1 + "/" + z1);
System.out.println("x2/y2/z2=" + x2 + "/" + y2 + "/" + z2);
// 向量的点乘
float vectorDot = x1*x2 + y1*y2 + z1*z2;
// 向量1的模
double vectorMold1 = Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2) + Math.pow(z1, 2));
// 向量2的模
double vectorMold2 = Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2) + Math.pow(z2, 2));
// 向量的夹角[0, PI],当夹角为锐角时,cosθ>0;当夹角为钝角时,cosθ<0
double cosAngle = vectorDot / (vectorMold1 * vectorMold2);
double radian = Math.acos(cosAngle);
return (float) (180 / Math.PI * radian);
}
Test Results