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

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

Math、Random类

Math

java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型- -般为double型。如果需要更加强大的数学运算能力,计算等数学中的相关内容,可以使用apache commons下面的Math类库。

Math类的常用方法:

1. abs绝对值

2. acos,asin,atan,cos,sin,tan三角函数

3. sqrt平方根

4. pow(double a, double b) a的b次幂

5. max(double a, double b)取大值

6. min(double a, double b)取小值

7. ceil(doublea)大于a的最小整数

8. floor(double a)小于a的最大整数

9.random()返回0.0到1.0的随机数

10 long round(double a) double型的数据a转换为long型(四舍五入)

11. toDegrees(double angrad)弧度->角度

12. toRadians(double angdeg)角度->弧度

Math类的常用方法

public class TestMath {      public static void main(string[]args){      //取整相关操作      System.out.println(Math.ceil(3.2));        System.out.println(Math.floor(3.2) );        System.out.println(Math.round(3.2));        System.out.println(Math.round(3.8));        // 绝对值、开方、a的b次幂等操作        System.out.println(Math.abs(-45));        System.out.println(Math.sqrt(64));        System.out.println(Math.pow(5,2));        System.out.print(Math.pow(2,5));        // Math类中的常量        System.out.println(Math.PI);        System.out.println(Math.E);        // 随机数        System.out.println(Math.random());// [0,1)	}}

Random类:

Math类中虽然为我们提供了产生随机数的方法Math.random(),但是通常我们需要的随机数范围并不是[0, 1]之间的double类型的数据,这就需要对其进行一些复杂的运算。如果使用Math.random()计算过于复杂的话,我们可以使用另外一种方式得到随机数,即Random类,这个类是专门用来生成随机数的,并且Math.random()底层调用的就是Random的nextDouble()方法。

Random类的常用方法:

import java.util.Random;      public class TestRandom {      public static void main(String[ args) {          Random rand = new Random();        // 随机生成[0,1)之间的double类型的数据        System.out.println(rand.nextDouble());        // 随机生成int类型允许范围之内的整型数据        System. out.println(rand.nextInt());        //随机生成[0,1)之间的float类型的救据        System.out.println(rand.nextFloat());        // 随机生成false或者true        System.out.println(rand.nextBoolean());        //随机生成[0,10]之间的int类型的数据        System.out.println(rand .nextInt(10));        // 随机生成[20,30]之间的int类型的数据        System.out.println(20+rand.nextInt(10));        // 随机生求[20,30)之间的int类型的数据(此种方法计算较为复杂)。        System.out.println(20+(int) (rand.nextDouble()*10));	}}

 

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

你可能感兴趣的文章
Mysql中存储引擎简介、修改、查询、选择
查看>>
Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
Mysql中常用函数的使用示例
查看>>
MySql中怎样使用case-when实现判断查询结果返回
查看>>
Mysql中怎样使用update更新某列的数据减去指定值
查看>>
Mysql中怎样设置指定ip远程访问连接
查看>>
mysql中数据表的基本操作很难嘛,由这个实验来带你从头走一遍
查看>>
Mysql中文乱码问题完美解决方案
查看>>
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
Mysql中的 IFNULL 函数的详解
查看>>
mysql中的collate关键字是什么意思?
查看>>
MySql中的concat()相关函数
查看>>
mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
查看>>
MySQL中的count函数
查看>>
MySQL中的DB、DBMS、SQL
查看>>
MySQL中的DECIMAL类型:MYSQL_TYPE_DECIMAL与MYSQL_TYPE_NEWDECIMAL详解
查看>>
MySQL中的GROUP_CONCAT()函数详解与实战应用
查看>>
MySQL中的IO问题分析与优化
查看>>