隨機數發生器及其簡單應用

Practice makes perfect!

隨機數產生原理:經典的隨機數產生方法爲是線性同餘法,即Linear Congruence Generator (LCG),由Lehmer於1951年提出。
同餘:對於兩個整數A,B,如果它們同時除以一個自然數M的餘數相同,就說A,B對於模M同餘,A \equiv B\ mod \ M

LCG 算法:

X_{n+1} = (aX_{n} + c) \ mod \ m 

X爲隨機序列,模除因子,a乘子(0 < a < m),c爲增量,或偏移量(0 < c < m),X_0稱爲初始種子。

如果m,a,c取值合適,序列最大週期將達到m。這種情況下,序列中所有可能的整數都在某點固定出現。當c=0時候,LCG就變換成了乘法同餘發生器,multiplicative congruential generator (MCG),c≠0時叫做混合同餘發生器,mixed congruential generator,MCG.

具體實現參見:wiki 隨機數產生原理

ANSI C標準規定rand()返回一個整數值,RAND_MAX通常不是很大。ANSI C標準要求RAND_MAX最大32767.

彙編語言實現猜隨機數遊戲:

;THis project decides to play the number game with computer !!! 
stack segment   stack
    dw  256 dup(0)
stack ends
    
data segment
data ends

code segment
    assume cs:code, ds:data
    
start:
    mov cx, 0 
    call random         ;get the random number 
    mov ax, bx
    mov bl, 10          ;convert Heximal to Decimal
    div bl
    mov ch, al 
j0: 
    mov ah, 01          ;receive data from keyboard
    int 21h
    mov bh, al
    sub bh, 30h
    mov ah, 01
    int 21h
    mov bl, al
    sub bl, 30h
    cmp bx, cx
    je  j1
    ja  j2
    jb  j3
j2:                     ;the input data is bigger than ranmdom number
    mov dl, 62
    mov ah, 2
    int 21h
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h 
    jmp j0
j3:                     ;the input data is smaller than random number
    mov dl, 60
    mov ah, 2
    int 21h
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h
    jmp j0
j1:                     ;the input data is equal to random data
    mov dl, 61
    mov ah, 2               
    int 21h 
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h    
    mov ax, 4c00h
    int 21h
random proc near        ;the random subprocess
    push cx
    push dx
    push ax
    sti                 ;Set Interrupt
    mov ah, 0
    int 1ah
    mov ax, dx
    and ah, 3
    mov dl, 101         ;generate 0~100 random number
    div dl
    mov bl, ah
    pop ax
    pop dx
    pop cx
    ret
random endp
    code ends
end start

C++實現猜隨機數遊戲:

#include<iostream>
#include<cstdlib>
#include<ctime>
#define random(a, b) (rand()%(b - a + 1) + a) //generate the random number in [a, b]

using namespace std;

int main()
{
	srand((unsigned)time(NULL));
	int rand_num = 0;
	int temp;
	rand_num = random(1, 100);
	cout << "Guess what number my brain has generated :" <<endl;
	cin >> temp;
	do
	{
		if (rand_num < temp)
		{
			cout << "	Your answer is too large " << endl;
		}
		else if (rand_num > temp)
		{
			cout << "	Your answer is too small " << endl;
		}
		else
		{
			cout << "good game, well done !" << endl;
		}
		cin >> temp;
	} while (rand_num != temp);
	cout << "good game, well done !" << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章