Java Math 类详解:常用数学运算方法全解析

1. 引言

在 Java 编程中,数学运算是最基础也是最常见的操作之一。无论是开发简单的计算器程序,还是实现复杂的科学计算、游戏物理引擎,都离不开数学函数的支持。Java 提供了 java.lang.Math 类来满足这些需求,它包含了执行基本数学运算的静态方法,如求绝对值、最大值、最小值、平方根、幂运算、三角函数等。

Math 类位于 java.lang 包中,这意味着我们无需显式导入即可直接使用。它被声明为 final 类,不能被继承,且其构造函数是私有的,因此无法实例化。所有方法都是 static 的,我们可以直接通过类名调用。

本文将全面介绍 Math 类的常用方法,包括基本运算、指数与对数、舍入与取整、三角函数、随机数生成等,并通过丰富的代码示例帮助读者快速掌握。

2. Math 类概述

2.1 类的定义

Math 类是 java.lang 包中的一个 final 类,定义如下:

java 复制代码
public final class Math {
    // 私有构造函数,防止实例化
    private Math() {}
    
    // 常量
    public static final double E = 2.7182818284590452354;
    public static final double PI = 3.14159265358979323846;
    
    // 各种静态方法...
}

2.2 重要常量

Math 类定义了两个重要的数学常量:

常量 值 说明
Math.PI 3.14159265358979323846 圆周率 π
Math.E 2.7182818284590452354 自然对数的底数 e

2.3 类特性

  • 不可继承 :final 类,不能被其他类继承。
  • 不可实例化 :构造函数为 private,无法创建对象。
  • 全部静态方法 :所有方法均为 static,通过类名直接调用。
  • 线程安全:所有方法都是线程安全的,不涉及共享可变状态。

3. 基本数学运算方法

3.1 绝对值方法 abs()

abs() 方法返回参数的绝对值,有四种重载形式:

java 复制代码
int abs(int a)
long abs(long a)
float abs(float a)
double abs(double a)
java 复制代码
public class AbsExample {
    public static void main(String[] args) {
        System.out.println(Math.abs(-10));      // 输出: 10
        System.out.println(Math.abs(-3.14));    // 输出: 3.14
        System.out.println(Math.abs(100L));     // 输出: 100
        System.out.println(Math.abs(-0.5f));    // 输出: 0.5
    }
}

注意事项:

  • 如果参数为 Integer.MIN_VALUE 或 Long.MIN_VALUE,由于溢出,返回值仍为负数本身。
  • 如果参数为 NaN,返回 NaN。
  • 如果参数为负零 -0.0,返回正零 0.0。

3.2 最大值与最小值方法 max() 和 min()

max() 返回两个参数中的较大值,min() 返回较小值:

java 复制代码
public class MaxMinExample {
    public static void main(String[] args) {
        // 整数比较
        System.out.println(Math.max(10, 20));       // 输出: 20
        System.out.println(Math.min(10, 20));       // 输出: 10
        
        // 浮点数比较
        System.out.println(Math.max(3.14, 2.71));   // 输出: 3.14
        System.out.println(Math.min(3.14, 2.71));   // 输出: 2.71
        
        // long 类型比较
        System.out.println(Math.max(1000000L, 999999L));  // 输出: 1000000
    }
}

注意事项:

  • 如果两个参数相等,返回第一个参数。
  • 如果参数中包含 NaN,返回 NaN。
  • 正零 0.0 大于负零 -0.0。

4. 指数与对数运算

4.1 幂运算 pow()

pow(double a, double b) 返回 a 的 b 次幂:

java 复制代码
public class PowExample {
    public static void main(String[] args) {
        System.out.println(Math.pow(2, 10));        // 输出: 1024.0
        System.out.println(Math.pow(3, 3));         // 输出: 27.0
        System.out.println(Math.pow(16, 0.5));      // 输出: 4.0(平方根)
        System.out.println(Math.pow(2, -2));        // 输出: 0.25
        System.out.println(Math.pow(10, 3));        // 输出: 1000.0
    }
}

4.2 平方根 sqrt()

sqrt(double a) 返回参数的平方根:

java 复制代码
public class SqrtExample {
    public static void main(String[] args) {
        System.out.println(Math.sqrt(16));      // 输出: 4.0
        System.out.println(Math.sqrt(2));       // 输出: 1.4142135623730951
        System.out.println(Math.sqrt(100));     // 输出: 10.0
        System.out.println(Math.sqrt(-1));      // 输出: NaN
    }
}

4.3 立方根 cbrt()

cbrt(double a) 返回参数的立方根:

java 复制代码
public class CbrtExample {
    public static void main(String[] args) {
        System.out.println(Math.cbrt(27));      // 输出: 3.0
        System.out.println(Math.cbrt(8));       // 输出: 2.0
        System.out.println(Math.cbrt(-64));     // 输出: -4.0
    }
}

4.4 自然对数 log()

log(double a) 返回参数的自然对数(以 e 为底):

java 复制代码
public class LogExample {
    public static void main(String[] args) {
        System.out.println(Math.log(Math.E));   // 输出: 1.0
        System.out.println(Math.log(1));        // 输出: 0.0
        System.out.println(Math.log(10));       // 输出: 2.302585092994046
        System.out.println(Math.log(100));      // 输出: 4.605170185988092
    }
}

4.5 以 10 为底的对数 log10()

log10(double a) 返回参数以 10 为底的对数:

java 复制代码
public class Log10Example {
    public static void main(String[] args) {
        System.out.println(Math.log10(1000));   // 输出: 3.0
        System.out.println(Math.log10(100));    // 输出: 2.0
        System.out.println(Math.log10(10));     // 输出: 1.0
        System.out.println(Math.log10(1));      // 输出: 0.0
    }
}

4.6 指数运算 exp()

exp(double a) 返回 e 的 a 次幂:

java 复制代码
public class ExpExample {
    public static void main(String[] args) {
        System.out.println(Math.exp(1));        // 输出: 2.718281828459045
        System.out.println(Math.exp(0));        // 输出: 1.0
        System.out.println(Math.exp(2));        // 输出: 7.38905609893065
    }
}

5. 舍入与取整方法

5.1 四舍五入 round()

round() 方法有两种重载形式:

java 复制代码
int round(float a)      // 返回最接近的整数
long round(double a)    // 返回最接近的 long 值
java 复制代码
public class RoundExample {
    public static void main(String[] args) {
        System.out.println(Math.round(3.4));    // 输出: 3
        System.out.println(Math.round(3.5));    // 输出: 4
        System.out.println(Math.round(3.6));    // 输出: 4
        System.out.println(Math.round(-3.4));   // 输出: -3
        System.out.println(Math.round(-3.5));   // 输出: -3
        System.out.println(Math.round(-3.6));   // 输出: -4
    }
}

注意 :round() 的舍入规则是「四舍五入」,但实际上是 floor(x + 0.5) 的结果。

5.2 向上取整 ceil()

ceil(double a) 返回大于或等于参数的最小整数(以 double 形式返回):

java 复制代码
public class CeilExample {
    public static void main(String[] args) {
        System.out.println(Math.ceil(3.1));     // 输出: 4.0
        System.out.println(Math.ceil(3.9));     // 输出: 4.0
        System.out.println(Math.ceil(4.0));     // 输出: 4.0
        System.out.println(Math.ceil(-3.1));    // 输出: -3.0
        System.out.println(Math.ceil(-3.9));    // 输出: -3.0
    }
}

5.3 向下取整 floor()

floor(double a) 返回小于或等于参数的最大整数(以 double 形式返回):

java 复制代码
public class FloorExample {
    public static void main(String[] args) {
        System.out.println(Math.floor(3.1));    // 输出: 3.0
        System.out.println(Math.floor(3.9));    // 输出: 3.0
        System.out.println(Math.floor(4.0));    // 输出: 4.0
        System.out.println(Math.floor(-3.1));   // 输出: -4.0
        System.out.println(Math.floor(-3.9));   // 输出: -4.0
    }
}

5.4 截断取整 rint()

rint(double a) 返回最接近参数的整数(以 double 形式返回),当距离相等时返回偶数:

java 复制代码
public class RintExample {
    public static void main(String[] args) {
        System.out.println(Math.rint(3.4));     // 输出: 3.0
        System.out.println(Math.rint(3.5));     // 输出: 4.0
        System.out.println(Math.rint(2.5));     // 输出: 2.0(偶数优先)
        System.out.println(Math.rint(3.6));     // 输出: 4.0
    }
}

6. 三角函数方法

6.1 正弦、余弦、正切

java 复制代码
public class TrigExample {
    public static void main(String[] args) {
        double angle = Math.PI / 6;  // 30 度
        
        System.out.println(Math.sin(angle));    // 输出: 0.49999999999999994
        System.out.println(Math.cos(angle));    // 输出: 0.8660254037844387
        System.out.println(Math.tan(angle));    // 输出: 0.5773502691896257
    }
}

6.2 反三角函数

java 复制代码
public class InverseTrigExample {
    public static void main(String[] args) {
        System.out.println(Math.asin(0.5));     // 输出: 0.5235987755982988(约 30 度)
        System.out.println(Math.acos(0.5));     // 输出: 1.0471975511965979(约 60 度)
        System.out.println(Math.atan(1));       // 输出: 0.7853981633974483(约 45 度)
        
        // atan2 返回从 x 轴到点 (x, y) 的角度
        System.out.println(Math.atan2(1, 1));   // 输出: 0.7853981633974483
    }
}

6.3 双曲函数

java 复制代码
public class HyperbolicExample {
    public static void main(String[] args) {
        System.out.println(Math.sinh(1));       // 输出: 1.1752011936438014
        System.out.println(Math.cosh(1));       // 输出: 1.5430806348152437
        System.out.println(Math.tanh(1));       // 输出: 0.7615941559557649
    }
}

6.4 角度与弧度转换

java 复制代码
public class AngleConversionExample {
    public static void main(String[] args) {
        // 角度转弧度
        System.out.println(Math.toRadians(180));    // 输出: 3.141592653589793
        System.out.println(Math.toRadians(90));     // 输出: 1.5707963267948966
        
        // 弧度转角度
        System.out.println(Math.toDegrees(Math.PI));    // 输出: 180.0
        System.out.println(Math.toDegrees(Math.PI / 2)); // 输出: 90.0
    }
}

7. 随机数生成

7.1 random() 方法

Math.random() 返回一个 [0.0, 1.0) 范围内的随机 double 值:

java 复制代码
public class RandomExample {
    public static void main(String[] args) {
        // 生成 [0, 1) 之间的随机数
        double random = Math.random();
        System.out.println("随机数: " + random);
        
        // 生成 [1, 100] 之间的随机整数
        int randomInt = (int)(Math.random() * 100) + 1;
        System.out.println("1-100 随机整数: " + randomInt);
        
        // 生成 [min, max] 之间的随机整数
        int min = 10, max = 20;
        int rangeRandom = (int)(Math.random() * (max - min + 1)) + min;
        System.out.println("10-20 随机整数: " + rangeRandom);
    }
}

7.2 与 Random 类的对比

虽然 Math.random() 使用方便,但在需要更精细控制时,推荐使用 java.util.Random 类:

java 复制代码
import java.util.Random;

public class RandomClassExample {
    public static void main(String[] args) {
        Random random = new Random();
        
        // 生成各种类型的随机数
        int randomInt = random.nextInt(100);        // [0, 100)
        long randomLong = random.nextLong();
        double randomDouble = random.nextDouble();  // [0.0, 1.0)
        boolean randomBoolean = random.nextBoolean();
        
        // 指定种子,可复现随机序列
        Random seededRandom = new Random(42);
        System.out.println(seededRandom.nextInt(100));
    }
}
7.2.1 多线程环境下的性能对比

在多线程环境下,Math.random() 和 java.util.Random 都存在性能瓶颈。Math.random() 内部使用一个静态的 Random 实例,多个线程并发调用时会因为共享同一个实例而产生竞争,导致性能下降。而 java.util.Random 虽然可以创建多个实例,但如果多个线程共享同一个实例,同样会因内部使用 CAS(比较并交换)操作更新种子而产生竞争。

相比之下,java.util.concurrent.ThreadLocalRandom 是专为多线程环境设计的随机数生成器。它为每个线程维护独立的随机数种子,避免了线程间的竞争,因此在并发场景下性能显著优于前两者。

推荐使用场景:

  • 高并发、多线程环境下需要生成随机数时,优先使用 ThreadLocalRandom。
  • 需要生成随机数但不关心可复现性的场景(如模拟、抽样、游戏逻辑等)。
  • 在 ForkJoinPool 或并行流(parallel stream)中生成随机数。
java 复制代码
import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {
    public static void main(String[] args) {
        // 生成 [0, 100) 之间的随机整数
        int randomInt = ThreadLocalRandom.current().nextInt(100);
        System.out.println("随机整数: " + randomInt);
        
        // 生成 [10, 20] 之间的随机整数(含边界)
        int rangeInt = ThreadLocalRandom.current().nextInt(10, 21);
        System.out.println("10-20 随机整数: " + rangeInt);
        
        // 生成随机 double 值 [0.0, 1.0)
        double randomDouble = ThreadLocalRandom.current().nextDouble();
        System.out.println("随机 double: " + randomDouble);
        
        // 生成随机 long 值
        long randomLong = ThreadLocalRandom.current().nextLong();
        System.out.println("随机 long: " + randomLong);
    }
}

注意 :ThreadLocalRandom 不支持指定种子,因此无法像 java.util.Random 那样复现随机序列。如果需要可复现的随机序列,应使用 java.util.Random 并指定种子。

8. 其他常用方法

8.1 符号函数 signum()

signum() 返回参数的符号:正数返回 1.0,负数返回 -1.0,零返回 0.0:

java 复制代码
public class SignumExample {
    public static void main(String[] args) {
        System.out.println(Math.signum(10));    // 输出: 1.0
        System.out.println(Math.signum(-10));   // 输出: -1.0
        System.out.println(Math.signum(0));     // 输出: 0.0
    }
}

8.2 取余运算 IEEEremainder()

IEEEremainder(double a, double b) 按照 IEEE 754 标准计算余数:

java 复制代码
public class RemainderExample {
    public static void main(String[] args) {
        // 与 % 运算符的区别
        System.out.println(Math.IEEEremainder(5, 2));   // 输出: 1.0
        System.out.println(5 % 2);                      // 输出: 1
        
        // 负数情况
        System.out.println(Math.IEEEremainder(-5, 2));  // 输出: -1.0
        System.out.println(-5 % 2);                     // 输出: -1
    }
}

8.3 精确加法、减法、乘法

Java 7 引入了精确运算方法,溢出时抛出 ArithmeticException:

java 复制代码
public class ExactArithmeticExample {
    public static void main(String[] args) {
        try {
            int result = Math.addExact(Integer.MAX_VALUE, 1);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("整数溢出: " + e.getMessage());
        }
        
        try {
            int result = Math.subtractExact(Integer.MIN_VALUE, 1);
        } catch (ArithmeticException e) {
            System.out.println("减法溢出: " + e.getMessage());
        }
        
        try {
            int result = Math.multiplyExact(100000, 100000);
        } catch (ArithmeticException e) {
            System.out.println("乘法溢出: " + e.getMessage());
        }
    }
}

8.4 最大值与最小值常量

java 复制代码
public class ConstantsExample {
    public static void main(String[] args) {
        // 整数类型的最大值和最小值
        System.out.println(Integer.MAX_VALUE);  // 输出: 2147483647
        System.out.println(Integer.MIN_VALUE);  // 输出: -2147483648
        System.out.println(Long.MAX_VALUE);     // 输出: 9223372036854775807
        
        // 浮点类型的特殊值
        System.out.println(Double.MAX_VALUE);   // 输出: 1.7976931348623157E308
        System.out.println(Double.MIN_VALUE);   // 输
相关推荐
是main不是漫39 分钟前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
bs_wa661 小时前
(赠源码)大学生社团管理系统72638-( java、PHP、python、C#、小程序、硬件、机器学习、大数据分析、深度学习,大屏、文案、毕设等)
java·spring boot·redis·mysql·tomcat·maven·idea
geovindu2 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
stormsha2 小时前
MySQL 连不上:2003 / 1045 / 1040 三张面孔与一个排查顺序
java·数据库·mysql
RobinXYuan2 小时前
【Java 字节码探秘】05 Modified UTF-8
java·jvm·源码阅读
Cosolar2 小时前
Kafka夺命连环问:吞吐、丢消息、重复与Rebalance,四个问题一套机制
java·后端·全栈
小盆女神节奶粉3 小时前
03-登录与RBAC
java·架构
星夜离尘563 小时前
MATLAB:两路读数平均相差 8 mV,换位能分出传感器偏差和通道偏差吗?
开发语言·matlab
时间的情敌3 小时前
Three.js 水位模拟、水体 Shader、罐体液位动态变化(水箱、水池、储罐液位)
开发语言·javascript·three.js