Upgrade to Pro — share decks privately, control downloads, hide ads and more …

基礎情報処理演習(補足)乱数の生成

 基礎情報処理演習(補足)乱数の生成

自然言語処理研究室

December 07, 2012
Tweet

More Decks by 自然言語処理研究室

Other Decks in Programming

Transcript

  1. プログラム例1: 0~1の乱数を生成 #include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> void

    main(void){ double p; srand(time(NULL)); p = (double) rand() / RAND_MAX; printf (“%f\n”, p); } 3
  2. プログラム例1: 0~1の乱数を生成 #include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> void

    main(void){ double p; srand(time(NULL)); p = (double) rand() / RAND_MAX; printf (“%f\n”, p); } 4 乱数の種を(プログラム 開始時刻で)決める。 最初に1回だけ実行する time関数のために必要
  3. プログラム例1: 0~1の乱数を生成 #include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> void

    main(void){ double p; srand(time(NULL)); p = (double) rand() / RAND_MAX; printf (“%f\n”, p); } 5 乱数(0~RAND_MAX間の ある整数)を生成する。 毎回数字が変わる。 srand関数とrand関数 のために必要
  4. プログラム例1: 0~1の乱数を生成 #include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> void

    main(void){ double p; srand(time(NULL)); p = (double) rand() / RAND_MAX; printf (“%f\n”, p); } 6 rand関数が生成する最大値 RAND_MAXが定義されている
  5. プログラム例2:サイコロ(1~6の乱数)を作る #include <stdio.h> #include <math.h> #include <time.h> void main(void){ int

    k; srand(time(NULL)); k = rand() % 6 + 1; printf (“%d\n”, k); } 7 rand()%6 はある整数を 6で割った余りなので、 0~5のいずれかの数字になる