目次

乱数

Math.random()

java.lang パッケージ の中の Mathというクラスの static なメソッドです。

Mathには sin, cos, tan, sqrt, log, log10 といった関数や、E, PI の定数が含まれます。

double un = Math.random();   //un に double (0~1)の値が入る。

RandChk1.java

public class RandChk1 { 
   public static void main( String[] args ) {
      int n = 1000;
      int[] ct = new int[8];
      int r;
      for ( int i=0 ; n > i ; i++ ){
        r = (int)( Math.random()* 6 + 1 );
        ct[r]++;
        if ( 15 > i ) System.out.print( r +" ");
      }
      System.out.println();
      for ( int i=0 ; ct.length > i ; i++ ){
            System.out.println( i + ":" + ct[i] );
      }
   }
}

結果はこうなります。

z3c3e@star00:~/java$ java RandChk1
4 4 3 4 6 3 6 1 3 6 3 6 2 5 5 
0:0
1:137
2:169
3:176
4:180
5:147
6:191
7:0
z3c3e@star00:~/java$ java RandChk1
3 6 3 6 3 4 2 5 4 4 5 4 2 3 2 
0:0
1:174
2:152
3:165
4:167
5:167
6:175
7:0

nextInt(int n)

java.util パッケージ の中の Randomというクラスのインスタンスメソッドです。0以上、n未満の整数を返します。

nextDouble() はMath.random()とおなじく0以上、1未満のdoubleを返します。

RandChk1.java

import java.util.Random;
public class RandChk2 { 
   public static void main( String[] args ) {
      int n = 1000;
      int[] ct = new int[8];
      int r;
      Random rd = new Random();  //乱数ジェネレータを作成
      //Random rd = new Random(4);
      for ( int i=0 ; n > i ; i++ ){
        r = rd.nextInt(6)+1 ;
        ct[r]++;
        if ( 15 > i ) System.out.print( r +" ");
      }
      System.out.println();
      for ( int i=0 ; ct.length > i ; i++ ){
            System.out.println( i + ":" + ct[i] );
      }
   }
}

z3c3e@star00:~/java$ java RandChk2
2 6 6 4 6 6 2 6 3 4 4 5 1 3 2 
0:0
1:151
2:151
3:156
4:168
5:194
6:180
7:0
z3c3e@star00:~/java$ java RandChk2
4 1 1 6 1 6 5 3 5 4 1 6 2 5 4 
0:0
1:151
2:154
3:172
4:171
5:172
6:180
7:0
もくじ

聖愛高等学校
http://www.seiai.ed.jp/
Last Modified