数学类

Math类


Java 中的 Math 类是 java.lang 包的一部分,提供了一系列的静态方法来实现数学运算,包括基本的算术运算、三角函数、指数和对数函数等。由于 Math 是一个 final 类,你不能继承它或实例化它。

以下是 Math 类的一些常用方法:

  1. 基本算术运算

    • abs: 绝对值
    • min: 最小值
    • max: 最大值
    • sqrt: 平方根
    • pow: 指数(幂次方)
  2. 三角函数

    • sin: 正弦
    • cos: 余弦
    • tan: 正切
    • asin: 反正弦(返回值在 -π/2 到 π/2 之间)
    • acos: 反余弦(返回值在 0 到 π 之间)
    • atan: 反正切
    • atan2: 从 xy 平面上某点 (x, y) 到原点 (0, 0) 的角度的反正切
  3. 指数和对数函数

    • exp: e 的指数
    • log: 自然对数(底数为 e)
    • log10: 以 10 为底的对数
  4. 圆周率和 Euler 数

    • PI: 圆周率的近似值
    • E: Euler 数的近似值
  5. 角度和弧度的转换

    • toRadians: 将角度转换为弧度
    • toDegrees: 将弧度转换为角度
  6. 随机数生成

    • random: 返回一个 [0.0, 1.0) 范围内的随机浮点数
  7. 舍入操作

    • round: 对浮点数进行四舍五入
  8. 符号操作

    • signum: 返回参数的符号函数

示例代码:

复制代码
public class MathExample {
    public static void main(String[] args) {
        // 基本算术运算
        int resultAbs = Math.abs(-5);
        double resultSqrt = Math.sqrt(16);
        double resultPow = Math.pow(2, 3);

        // 三角函数
        double resultSin = Math.sin(Math.toRadians(30));
        double resultCos = Math.cos(Math.toRadians(60));

        // 指数和对数函数
        double resultExp = Math.exp(1);
        double resultLog = Math.log(10);
        double resultLog10 = Math.log10(100);

        // 随机数生成
        double randomDouble = Math.random();

        // 舍入操作
        int resultRound = Math.round(3.7);

        System.out.println("abs(-5): " + resultAbs);
        System.out.println("sqrt(16): " + resultSqrt);
        System.out.println("pow(2, 3): " + resultPow);
        System.out.println("sin(30°): " + resultSin);
        System.out.println("cos(60°): " + resultCos);
        System.out.println("exp(1): " + resultExp);
        System.out.println("log(10): " + resultLog);
        System.out.println("log10(100): " + resultLog10);
        System.out.println("random(): " + randomDouble);
        System.out.println("round(3.7): " + resultRound);
    }
}

Math 类是 Java 程序中进行数学运算的基础工具,它的静态方法可以满足大多数数学计算的需求。

posted @   墨澜  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示