很多论坛里都有朋友询问有关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)之间。
细心的朋友发现每次第一次产生的数其实未必随机,都是固定的,只是后面每个数不一样罢了。因此这种随机算法受到了局限,很多随机函数还与时间函数相关联,这样只要不在同一时刻产生的数就不会一样了,当然精确到毫秒级别同一时刻是相对困难的。
故,以上算法适用与连续不断产生随机数的需求,如果系统重置,每次重置所产生的随机数是相同的,这一点需要注意。
源代码下载处:
本文介绍了如何使用C#在VS2005中实现随机数生成,核心代码涉及next乘以1103515245加上12345,返回值通过除以65536再取模32768,确保范围在0到32767之间。虽然首次生成的随机数固定,但后续会产生不同数值。注意,若需全局唯一,通常会结合时间函数。提供源码下载链接。

1万+

被折叠的 条评论
为什么被折叠?



