1. 程式人生 > >JAVA Math類與Random類

JAVA Math類與Random類

Math類與Random類

Math類

Math類中包含了一些數學計算的方法。 Math類的構造方法被私有化,不能例項化物件。

成員變數

Math類有兩個靜態成員變數用來表示自然底數和圓周率。 public static final double E : 自然底數 public static final double PI: 圓周率 可以使用Math.PI和Math.E來呼叫。

成員方法

public static double cos(double a) 返回角的三角餘弦。 public static double sin(double a) 返回角的三角正弦。 public static double tan(double a) 返回角的三角正切 。 public static int abs ( int a)取絕對值 public static double ceil ( double a)向上取整 public static double floor ( double a)向下取整 public static int max ( int a, int b)獲取最大值 public static int min ( int a, int b)獲取最小值 public static double pow ( double a, double b)獲取a的b次冪 public static double random () 獲取隨機數 返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0。 public static int round ( float a)四捨五入 public static double sqrt ( double a)獲取正平方根

public class MathDemo {
    public static void main(String[] args) {
        //Math類的成員方法使用
        System.out.println(Math.PI);
        System.out.println(Math.E);
        System.out.println(Math.cos(Math.PI/2));//0
        System.out.println(Math.sin(Math.PI/2));//1
        System.out.println(Math.ceil(3.14
));//4 System.out.println(Math.floor(3.14));//3 System.out.println(Math.min(3.14,3)//3 System.out.println(Math.max(100, Math.max(10, 20)));//100 System.out.println(Math.pow(2,3));//2的立方 int num= (int) (Math.random()*100+1);//產生1-100的隨機數 System.out.println(Math.round(3.56))
;//4.0 System.out.println(Math.sqrt(4));//2 //求立方根 System.out.println(Math.pow(9.0, 1.0 / 3.0));//3 System.out.println(0.9999999999999999999999999==1);//true } }

Random類

Random類用於產生隨機數,如果使用相同的種子來產生隨機數,則每次呼叫產生的隨機數序列都相同。

構造方法

Random() 建立一個新的隨機數生成器。 Random(long seed) 使用單個 long 種子建立一個新的隨機數生成器。

成員方法

public double nextDouble() 返回下一個偽隨機數,它是取自此隨機數生成器序列的、在 0.0 和 1.0 之間均勻分佈的 double 值。 public float nextFloat() 返回下一個偽隨機數,它是取自此隨機數生成器序列的、在 0.0 和 1.0 之間均勻分佈的 float 值。 public int nextInt() 返回下一個偽隨機數,它是此隨機數生成器的序列中均勻分佈的 int 值。 public int nextInt(int n) 返回一個偽隨機數,它是取自此隨機數生成器序列的、在 0(包括)和指定值(不包括)之間均勻分佈的 int 值。 public long nextLong() 返回下一個偽隨機數,它是取自此隨機數生成器序列的均勻分佈的 long 值。

public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int i1 = random.nextInt();//生成隨機的整數再int範圍
        int i2 = random.nextInt(100);//生成的隨機數 0--99
        for (int i1 = 0; i1 < 100; i1++) {
           int i = random.nextInt(100);//生成隨機的整數再int範圍
            System.out.println(i);
            System.out.println(i);
        }
    }
}

而如果使用種子建立隨機數生成器,則每次調用出現的隨機數序列一致。

public class RandomDemo2 {
    public static void main(String[] args) {
        //使用單個 long 種子建立一個新的隨機數生成器。
        Random random = new Random(100L);
        for (int i = 0; i < 10; i++) {//每次執行都是5 0 4 8 1 6 6 8 3 3
            int i1 = random.nextInt(10);
            System.out.println(i1);
        }
    }
}