欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个随机数类

程序员文章站 2022-07-01 23:02:31
本类思想:高性能计数器以微妙级累加数值,逢十进位。如果动态的单看数值最后一个数字,一定是在0-9之间不断旋转,就像一个滚动的俄罗斯轮盘,暂停时一定指向其中某一位数字并且指向哪个数字是不可预测的,当暂停次数足够多时,分布在各个数值上的概率无限接近。 写作时间:2018-11-07 本文只代表本人的见解 ......

       本类思想:高性能计数器以微妙级累加数值,逢十进位。如果动态的单看数值最后一个数字,一定是在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

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

一个随机数类