Java Math 類別

java.lang.Math 類別提供常用的數學運算方法。

常數

Math.PI;   // 3.141592653589793
Math.E;    // 2.718281828459045

基本運算

絕對值

Math.abs(-10);     // 10
Math.abs(-3.14);   // 3.14

最大值和最小值

Math.max(10, 20);  // 20
Math.min(10, 20);  // 10

// 多個數
int max = Math.max(Math.max(a, b), c);

// 使用 Stream
int max = IntStream.of(a, b, c, d).max().orElse(0);

次方和平方根

Math.pow(2, 3);    // 8.0(2³)
Math.sqrt(16);     // 4.0(√16)
Math.cbrt(27);     // 3.0(∛27)

指數和對數

Math.exp(1);       // 2.718...(e¹)
Math.log(Math.E);  // 1.0(ln(e))
Math.log10(100);   // 2.0(log₁₀(100))

進位

// 四捨五入
Math.round(3.5);   // 4
Math.round(3.4);   // 3
Math.round(-3.5);  // -3

// 無條件進位
Math.ceil(3.1);    // 4.0
Math.ceil(-3.1);   // -3.0

// 無條件捨去
Math.floor(3.9);   // 3.0
Math.floor(-3.9);  // -4.0

三角函數

參數是弧度:

// 角度轉弧度
double radians = Math.toRadians(90);  // π/2

// 弧度轉角度
double degrees = Math.toDegrees(Math.PI);  // 180

// 三角函數
Math.sin(Math.PI / 2);  // 1.0
Math.cos(0);            // 1.0
Math.tan(Math.PI / 4);  // 1.0

// 反三角函數
Math.asin(1);           // π/2
Math.acos(0);           // π/2
Math.atan(1);           // π/4

隨機數

// 0.0 到 1.0(不含)
double random = Math.random();

// 0 到 99
int randomInt = (int) (Math.random() * 100);

// 1 到 100
int randomRange = (int) (Math.random() * 100) + 1;

// 使用 Random 類別(更好)
Random random = new Random();
int n = random.nextInt(100);      // 0 到 99
int m = random.nextInt(100) + 1;  // 1 到 100
double d = random.nextDouble();   // 0.0 到 1.0
boolean b = random.nextBoolean();

更多說明請參考 Java 隨機數

其他方法

// 符號
Math.signum(10);   // 1.0
Math.signum(-10);  // -1.0
Math.signum(0);    // 0.0

// 複製符號
Math.copySign(5, -1);  // -5.0
Math.copySign(-5, 1);  // 5.0

// 斜邊
Math.hypot(3, 4);  // 5.0(√(3² + 4²))

// 較大者(數學)
Math.floorDiv(7, 3);   // 2
Math.floorMod(7, 3);   // 1

// 精確運算(溢位時拋出例外)
Math.addExact(1, 2);
Math.multiplyExact(10, 20);
Math.incrementExact(5);

實際應用

計算距離

public static double distance(double x1, double y1, double x2, double y2) {
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}

圓面積和周長

public static double circleArea(double radius) {
    return Math.PI * Math.pow(radius, 2);
}

public static double circleCircumference(double radius) {
    return 2 * Math.PI * radius;
}

限制範圍

public static int clamp(int value, int min, int max) {
    return Math.max(min, Math.min(max, value));
}

// 或使用 Java 21+ 的 Math.clamp
Math.clamp(value, min, max);

隨機整數範圍

public static int randomInt(int min, int max) {
    return (int) (Math.random() * (max - min + 1)) + min;
}

Math 方法總覽

方法說明
abs(x)絕對值
max(a, b)最大值
min(a, b)最小值
pow(a, b)a 的 b 次方
sqrt(x)平方根
cbrt(x)立方根
round(x)四捨五入
ceil(x)無條件進位
floor(x)無條件捨去
random()隨機數 0~1
sin/cos/tan(x)三角函數
log(x)自然對數
log10(x)以 10 為底的對數
exp(x)e 的 x 次方