Java實現的平面向量基本運算,其中涉及到了有關數學方面的角度、弧度轉換的基本問題,記錄一下,感覺大學學的線性代數都忘記的差不多了=.=
下面是一個Vector2D的向量類,里面封裝了一些關於向量的基本運算的函數。
//平面向量(x,y)的基本運算規則,角度弧度的轉換等實現 public class Vector2D { private double x; private double y; public Vector2D() { x = 0; y = 0; } public Vector2D(double _x, double _y) { x = _x; y = _y; } //獲取弧度 public double getRadian() { return Math.atan2(y, x); } //獲取角度 public double getAngle() { return getRadian() / Math.PI * 180; } public Vector2D clone() { return new Vector2D(x,y); } public double getLength() { return Math.sqrt(getLengthSQ()); } public double getLengthSQ() { return x * x + y * y; } //向量置零 public Vector2D Zero() { x = 0; y = 0; return this; } public boolean isZero() { return x == 0 && y == 0; } //向量的長度設置為我們期待的value public void setLength(double value) { double _angle = getAngle(); x = Math.cos(_angle) * value; y = Math.sin(_angle) * value; } //向量的標准化(方向不變,長度為1) public Vector2D normalize() { double length = getLength(); x = x / length; y = y / length; return this; } //是否已經標准化 public boolean isNormalized() { return getLength() == 1.0; } //向量的方向翻轉 public Vector2D reverse() { x = -x; y = -y; return this; } //2個向量的數量積(點積) public double dotProduct(Vector2D v) { return x * v.x + y * v.y; } //2個向量的向量積(叉積) public double crossProduct(Vector2D v) { return x * v.y - y * v.x; } //計算2個向量的夾角弧度 //參考點積公式:v1 * v2 = cos<v1,v2> * |v1| *|v2| public static double radianBetween(Vector2D v1, Vector2D v2) { if(!v1.isNormalized()) v1 = v1.clone().normalize(); // |v1| = 1 if(!v2.isNormalized()) v2 = v2.clone().normalize(); // |v2| = 1 return Math.acos(v1.dotProduct(v2)); } //弧度 = 角度乘以PI后再除以180、 推理可得弧度換算角度的公式 //弧度轉角度 public static double radian2Angle(double radian) { return radian / Math.PI * 180; } //向量加 public Vector2D add(Vector2D v) { return new Vector2D(x + v.x, y + v.y); } //向量減 public Vector2D subtract(Vector2D v) { return new Vector2D(x - v.x, y - v.y); } //向量乘 public Vector2D multiply(double value) { return new Vector2D(x * value, y * value); } //向量除 public Vector2D divide(double value) { return new Vector2D(x / value, y / value); } }