一个随机数类
Posted j20171203
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个随机数类相关的知识,希望对你有一定的参考价值。
本类思想:高性能计数器以微妙级累加数值,逢十进位。如果动态的单看数值最后一个数字,一定是在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() + " "); }
写作时间:2018-11-07
=====================================================================================
本文只代表本人的见解,可能存在错误,仅用于技术交流。如果你喜欢该文,可以扫下面的二维码打赏我(打赏敬请备注“博客园打赏”五字)。
以上是关于一个随机数类的主要内容,如果未能解决你的问题,请参考以下文章