使用VS2005 C#編寫隨機數Random算法的代碼

很多論壇裏都有朋友詢問有關random實現隨機取數的算法原理,因爲工作的需要,參考了網絡的文章寫了一個簡單的code,如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace RandomFunction
{
    
public partial class Random : Form
    
{
        
public Random()
        
{
            InitializeComponent();
        }


        
private void btnExit_Click(object sender, EventArgs e)
        
{
            Application.Exit();
        }


        
static UInt64 next = 1;

        
//從同一個種子開始
        private int PeRandom(  )
        
{
            next 
= next * 1103515245 + 12345;
            
return (UInt16)(next / 65536% 32768;
        }


        
private void btnRandom_Click(object sender, EventArgs e)
        
{
            
int input_MaxNum;
            
int output_num;

            
//輸入隨機數的範圍 0 --- input_MaxNum
            input_MaxNum = int.Parse(inputRandom.Text);

            output_num 
= this.PeRandom();

            
try
            
{
                listOutput.Items.Add(output_num 
% input_MaxNum);
            }

            
catch (System.ApplicationException ex)
            
{
                Console.WriteLine(ex.Message);
            }



        }


        
private void btnClr_Click(object sender, EventArgs e)
        
{
            listOutput.Items.Clear();
        }


    }

}

下面這段代碼是隨機函數的核心部分:

next = next * 1103515245 + 12345;
return (UInt16)(next / 65536) % 32768;

讀者可以嘗試着把1103515245,12345替換掉,也會產生隨機數,next / 65536相當於把next向右移16位,然後% 32768,因此取值範圍在(0--32767)之間。

細心的朋友發現每次第一次產生的數其實未必隨機,都是固定的,只是後面每個數不一樣罷了。因此這種隨機算法受到了侷限,很多隨機函數還與時間函數相關聯,這樣只要不在同一時刻產生的數就不會一樣了,當然精確到毫秒級別同一時刻是相對困難的。

故,以上算法適用與連續不斷產生隨機數的需求,如果系統重置,每次重置所產生的隨機數是相同的,這一點需要注意。

源代碼下載處:

http://download.csdn.net/source/334547

發佈了17 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章