VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之一个随机数类

      本类思想:高性能计数器以微妙级累加数值,逢十进位。如果动态的单看数值最后一个数字,一定是在0-9之间不断旋转,就像一个滚动的俄罗斯轮盘,暂停时一定指向其中某一位数字并且指向哪个数字是不可预测的,当暂停次数足够多时,分布在各个数值上的概率无限接近。

复制代码
using System.Runtime.InteropServices;

namespace SuiJiShu
{
    /// <summary>
    /// 随机数生成器
    /// </summary>
    public class SuiJiShuShengChengQi
    {
        //获取高性能计数器数值
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);

        /// <summary>
        /// 十以内随机数
        /// </summary>
        /// <returns></returns>
        public int ShiYiNeiSuiJiShu()
        {
            long _dangQianJiShuQiZhi = 0;
            QueryPerformanceCounter(ref _dangQianJiShuQiZhi);

            string _dangQianJiShuQiZhiString = _dangQianJiShuQiZhi.ToString();
            return int.Parse(_dangQianJiShuQiZhiString.Remove(0, _dangQianJiShuQiZhiString.Length - 1));
        }
        /// <summary>
        /// 百以内随机数
        /// </summary>
        /// <returns></returns>
        public int BaiYiNeiSuiJiShu()
        {
            long _dangQianJiShuQiZhi = 0;
            QueryPerformanceCounter(ref _dangQianJiShuQiZhi);

            string _dangQianJiShuQiZhiString = _dangQianJiShuQiZhi.ToString();
            return int.Parse(_dangQianJiShuQiZhiString.Remove(0, _dangQianJiShuQiZhiString.Length - 2));
        }
        /// <summary>
        /// 千以内随机数
        /// </summary>
        /// <returns></returns>
        public int QianYiNeiSuiJiShu()
        {
            long _dangQianJiShuQiZhi = 0;
            QueryPerformanceCounter(ref _dangQianJiShuQiZhi);

            string _dangQianJiShuQiZhiString = _dangQianJiShuQiZhi.ToString();
            return int.Parse(_dangQianJiShuQiZhiString.Remove(0, _dangQianJiShuQiZhiString.Length - 3));
        }
    }
}
复制代码
复制代码
//ShiYiNeiSuiJiShu运行一百万次数值分布:
0:97872
1:100082
2:100237
3:99895
4:100556
5:99995
6:100384
7:99928
8:100339
9:100712

//测试代码
Dictionary<int, List<int>> _tongJiZiDian = new Dictionary<int, List<int>>();
for (int i = 0; i < 10; i++)
{
    _tongJiZiDian.Add(i, new List<int>());
}

SuiJiShuShengChengQi _SuiJiShuShengChengQi = new SuiJiShuShengChengQi();
for (int i = 0; i < 1000000; i++)
{
   int _suiJiShu = _SuiJiShuShengChengQi.ShiYiNeiSuiJiShu();
   _tongJiZiDian[_suiJiShu].Add(_suiJiShu);
}

StringBuilder _sss = new StringBuilder();
foreach (KeyValuePair<int, List<int>> key in _tongJiZiDian)
{
  _sss.Append(key.Key.ToString() + ":" + key.Value.Count.ToString() + "\r\n");
}   
复制代码

 

写作时间:2018-11-07

=====================================================================================
本文只代表本人的见解,可能存在错误,仅用于技术交流。如果你喜欢该文,可以扫下面的二维码打赏我(打赏敬请备注“博客园打赏”五字)。


相关教程