JavaSE 基礎強化(31):Math 類常用方法、字段與實戰案例全解析
Math 類概覽
- 包路徑:
java.lang.Math(無需導入)。
- 所有方法均為
static,直接 Math.方法名() 調用。
- 不可實例化(構造器私有),無子類。
核心常用方法速查表
| 方法 | 說明 | 示例 | 結果 |
abs(x) | 絕對值 | Math.abs(-5) | 5 |
max(a,b) / min(a,b) | 最大/最小值 | Math.max(3,7) | 7 |
round(x) | 四捨五入(float→int, double→long) | Math.round(2.6) | 3 |
ceil(x) | 向上取整 | Math.ceil(2.1) | 3.0 |
floor(x) | 向下取整 | Math.floor(2.9) | 2.0 |
sqrt(x) | 平方根 | Math.sqrt(16) | 4.0 |
pow(a,b) | a 的 b 次冪 | Math.pow(2,3) | 8.0 |
random() | 返回 [0.0, 1.0) 隨機 double | Math.random() | 0.732... |
log(x) | 自然對數 (底數 e) | Math.log(Math.E) | 1.0 |
log10(x) | 底數 10 對數 | Math.log10(100) | 2.0 |
sin/cos/tan | 三角函數(參數為弧度) | Math.sin(Math.PI/2) | 1.0 |
toRadians(deg) | 角度轉弧度 | Math.toRadians(180) | 3.14159... |
toDegrees(rad) | 弧度轉角度 | Math.toDegrees(Math.PI) | 180.0 |
常數字段
Math.E // 2.718281828459045 (自然對數底數 e)
Math.PI // 3.141592653589793 (圓周率 π)
實戰案例 1:生成 10 個 0-9 隨機整數填充數組
public class RandomArrayDemo {
public static void main(String[] args) {
int[] nums = new int[10];
for (int i = 0; i < nums.length; i++) {
// Math.random() -> [0,1) * 10 -> [0,10) -> 強轉 int -> [0,9]
nums[i] = (int) (Math.random() * 10);
}
System.out.println(Arrays.toString(nums));
// 輸出示例:[3, 7, 0, 9, 2, 5, 1, 8, 4, 6]
}
}
實戰案例 2:計算兩點間歐氏距離
public class DistanceDemo {
public static void main(String[] args) {
double x1 = 3, y1 = 4;
double x2 = 0, y2 = 0;
double dist = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
System.out.printf("距離: %.2f%n", dist); // 5.00
}
}
實戰案例 3:綜合演示
public class MathComprehensiveDemo {
public static void main(String[] args) {
double a = Math.round(Math.random() * 10); // 0-10 隨機整數
double b = Math.round(Math.random() * 10);
System.out.println("a = " + a + ", b = " + b);
System.out.println("hypot(a,b) = " + Math.hypot(a, b)); // √(a²+b²) 避免溢出
System.out.println("pow(a,3) = " + Math.pow(a, 3)); // a³
System.out.println("round(b) = " + Math.round(b)); // 長整型
System.out.println("log(e^15) = " + Math.log(Math.pow(Math.E, 15))); // 15.0
System.out.println("toRadians(60) = " + Math.toRadians(60)); // π/3
System.out.println("toDegrees(π/4) = " + Math.toDegrees(Math.PI/4)); // 45.0
}
}
進階補充:Java 17+ 新增方法
| 方法 | 說明 |
Math.clamp(value, min, max) | 將值限制在 [min, max] 區間(Java 21+) |
Math.fma(a, b, c) | 融合乘加:a × b + c,單次圓整,精度更高 |
Math.ulp(x) | 返回單位在最後一位(精度分析用) |
避坑指南
- random() 範圍陷阱:
Math.random() * n 產生 [0, n),若需 [1, n] 用 (int)(Math.random() * n) + 1。
- 大數精度:金融計算嚴禁用
double/float,必須用 BigDecimal。
- 性能敏感場景:
Math.sqrt、Math.pow 較重,熱路徑可考慮查表或近似算法。
StrictMath 替代:嚴格遵循 IEEE 754,跨平台位級一致,性能稍慢。
總結
Math 類是 Java 基礎數學運算的工具箱,掌握其常用方法、常數與邊界行為,能顯著提升數值計算代碼的可讀性與正確性。實戰中結合 Random 類(更靈活的隨機數生成)與 BigDecimal(精確計算),構建健壯的數值處理體系。