博客
关于我
Math、Random类
阅读量:558 次
发布时间:2019-03-09

本文共 1774 字,大约阅读时间需要 5 分钟。

好的,我将基于您的要求对文本进行优化:


Java 中的 Math 类与 Random 类

Math 类

Java 的 java.lang.Math 类提供了一系列静态方法,用于执行基本的科学计算。这些方法的参数和返回值通常为 double 类型。如果需要更强大的数学功能,可以考虑使用 Apache Commons Math 或其他高级库。

常用 Method

  • 绝对值

    Math.abs(double a)
    返回输入值的绝对值。

  • 三角函数

    acos, asin, atan, cos, sin, tan
    用于执行基本三角函数运算。

  • 平方根

    Math.sqrt(double a)
    返回输入值的平方根。

  • 幂运算

    Math.pow(double a, double b)
    返回 ab 次幂。

  • 最大值与最小值

    Math.max(double a, double b), Math.min(double a, double b)
    返回两个数中的最大值或最小值。

  • 取整运算

    Math.ceil(double a)
    返回大于 a 的最小整数。
    Math.floor(double a)
    返回小于 a 的最大整数。
    Math.round(double a)
    double 转换为相应的 long 类型(四舍五入)。

  • 随机数生成

    Math.random()
    返回区间 [0, 1) 之间的 double 类型随机数。

  • 弧度与角度转换

    Math.toDegrees(double radian)
    将弧度转换为角度。
    Math.toRadians(double degree)
    将角度转换为弧度。


  • 随机数生成(Random 类)

    虽然 Math.random() 方法能够生成随机数,但如果需要更灵活的随机数范围和类型,可以使用 Random 类。这个类专门用于生成各种类型的随机数,Math.random() 实际上调用了 RandomnextDouble() 方法。

    Random 类的常用 Method
  • 生成 double 类型随机数

    Random.random()
    返回区间 [0, 1) 之间的 double 随机数。

  • 生成 int 类型随机数

    Random.nextInt()
    返回区间 [Integer.MIN_VALUE, Integer.MAX_VALUE) 之间的 int 随机数。

  • 生成 float 类型随机数

    Random.nextFloat()
    返回区间 [0.0f, 1.0f) 之间的 float 随机数。

  • 生成布尔值

    Random.nextBoolean()
    返回 truefalse

  • 范围限制的整数生成

    Random.nextInt(int range)
    返回区间 [0, range) 之间的 int 随机数。
    Random.nextDouble(int range)
    返回区间 [0.0, range) 之间的 double 随机数。


  • 示例代码

    import java.util.Random;public class TestRandom {    public static void main(String[] args) {        Random rand = new Random();        System.out.println(rand.nextDouble()); // [0,1) 之间的双精度随机数        System.out.println(rand.nextInt()); // [-2^31, 2^31-1] 之间的整数起点        System.out.println(rand.nextFloat()); // [0.0f, 1.0f) 之间的单精度随机数        System.out.println(rand.nextBoolean()); // 布尔值随机生成        System.out.println(rand.nextInt(10)); // [0,10) 之间的整数起点    }}

    这篇文章清晰地介绍了 Math 类和 Random 类的功能,内容结构合理,便于搜索引擎爬取和索引,同时保持了技术内容的准确性和可读性。

    转载地址:http://ywgsz.baihongyu.com/

    你可能感兴趣的文章
    pytest实战技巧之参数化应用!
    查看>>
    Pytest实践:Python测试技术基础知识!
    查看>>
    Pytest接口自动化测试实战演练
    查看>>
    Pytest插件pytest-selenium-让自动化测试更简洁
    查看>>
    Pytest数据驱动怎么玩?实战教程来了!
    查看>>
    Pytest数据驱动怎么玩?实战教程来了!
    查看>>
    pytest文档25-conftest.py作用范围
    查看>>
    Pytest框架 之【用例执行顺序】
    查看>>
    Pytest框架中的测试用例执行方式!
    查看>>
    pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
    查看>>
    Pytest框架环境切换实战教程!赶快收藏
    查看>>
    Pytest测试实战|Conftest.py详解
    查看>>
    Pytest测试框架快速搭建
    查看>>
    pytest测试框架:最强大的自动化测试工具,让测试变得轻松有趣
    查看>>
    pytest简介及jenkins集成
    查看>>
    Pytest自动化框架运行全局配置文件pytest.ini
    查看>>
    pytest自动化测试-Git中的测试用例运行
    查看>>
    Pytest自动化测试-简易入门教程(01)
    查看>>
    Pytest自动化测试-简易入门教程(02)
    查看>>
    Pytest自动化测试-简易入门教程(03)
    查看>>