博客
关于我
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/

    你可能感兴趣的文章
    Python pytest 面试题!
    查看>>
    Python pytz 时区函数返回一个相差 9 分钟的时区
    查看>>
    python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
    查看>>
    Python random和json模块
    查看>>
    Python random模块seed理解
    查看>>
    python range()函数
    查看>>
    Python rdflib可传递查询
    查看>>
    python redis 集群_python 搭建redis集群
    查看>>
    python redis连接,在Python中使用Redis连接池的正确方法
    查看>>
    python regex_Python RegEx
    查看>>
    python requests post 中文结果请求得到unicode
    查看>>
    Python Requests接口自动化测试实战
    查看>>
    Python requests模块
    查看>>
    python request与grequests该如何选择
    查看>>
    python request模块
    查看>>
    Python requirements.txt的使用方法
    查看>>
    Python REST(Web 服务)框架的推荐?
    查看>>
    Python rsa 加密
    查看>>
    Python RSA操作
    查看>>
    Python轻松实现统计学中重要的相关性分析
    查看>>