Java 三角函數
Java Math 類別提供完整的三角函數運算方法。
基本三角函數
// 角度轉弧度(Java 三角函數使用弧度)
double radians = Math.toRadians(90); // π/2
// 正弦 sin
System.out.println(Math.sin(Math.toRadians(0))); // 0.0
System.out.println(Math.sin(Math.toRadians(30))); // 0.5
System.out.println(Math.sin(Math.toRadians(90))); // 1.0
// 餘弦 cos
System.out.println(Math.cos(Math.toRadians(0))); // 1.0
System.out.println(Math.cos(Math.toRadians(60))); // 0.5
System.out.println(Math.cos(Math.toRadians(90))); // ≈0(有浮點誤差)
// 正切 tan
System.out.println(Math.tan(Math.toRadians(0))); // 0.0
System.out.println(Math.tan(Math.toRadians(45))); // 1.0
反三角函數
// 反正弦 asin(回傳弧度)
double angle = Math.asin(0.5);
System.out.println(Math.toDegrees(angle)); // 30.0
// 反餘弦 acos
double angle2 = Math.acos(0.5);
System.out.println(Math.toDegrees(angle2)); // 60.0
// 反正切 atan
double angle3 = Math.atan(1);
System.out.println(Math.toDegrees(angle3)); // 45.0
// atan2(考慮象限的反正切)
double angle4 = Math.atan2(1, 1); // atan2(y, x)
System.out.println(Math.toDegrees(angle4)); // 45.0
雙曲函數
// 雙曲正弦 sinh
System.out.println(Math.sinh(0)); // 0.0
System.out.println(Math.sinh(1)); // 1.1752...
// 雙曲餘弦 cosh
System.out.println(Math.cosh(0)); // 1.0
// 雙曲正切 tanh
System.out.println(Math.tanh(0)); // 0.0
角度與弧度轉換
// 角度轉弧度
double radians = Math.toRadians(180); // π
System.out.println(radians); // 3.141592653589793
// 弧度轉角度
double degrees = Math.toDegrees(Math.PI); // 180
System.out.println(degrees); // 180.0
// 圓周率常數
System.out.println(Math.PI); // 3.141592653589793
實用範例
計算兩點間角度
public static double angleBetween(double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
return Math.toDegrees(Math.atan2(dy, dx));
}
System.out.println(angleBetween(0, 0, 1, 1)); // 45.0
System.out.println(angleBetween(0, 0, 0, 1)); // 90.0
System.out.println(angleBetween(0, 0, -1, 0)); // 180.0
圓周上的座標
public static double[] pointOnCircle(double centerX, double centerY,
double radius, double angleDegrees) {
double radians = Math.toRadians(angleDegrees);
double x = centerX + radius * Math.cos(radians);
double y = centerY + radius * Math.sin(radians);
return new double[]{x, y};
}
double[] point = pointOnCircle(0, 0, 10, 45);
System.out.printf("(%.2f, %.2f)%n", point[0], point[1]); // (7.07, 7.07)
計算三角形面積
// 使用兩邊和夾角
public static double triangleArea(double a, double b, double angleDegrees) {
double radians = Math.toRadians(angleDegrees);
return 0.5 * a * b * Math.sin(radians);
}
System.out.println(triangleArea(10, 10, 90)); // 50.0
重點整理
- Java 三角函數使用弧度,非角度
- 使用
Math.toRadians()和Math.toDegrees()轉換 Math.atan2(y, x)可正確處理所有象限- 浮點運算會有微小誤差
Math.PI提供圓周率常數