随机函数

来源:互联网 发布:协同过滤算法的优缺点 编辑:程序博客网 时间:2024/06/03 09:27


前言

随机数是人们生活中的必需品,比如说喝酒时的划拳,骰子,国人喜欢的斗地主,麻将,福彩,游戏中那就跟不用说了。所以说随机数的设计是关乎公平性最重要的决定因素。如果说前面提到的事件都可以预测的话,我想没有人会去参与这些事件。

随机数的用途

  • 数学 (统计计算, 模拟)
  • 游戏(随机掉落宝物,爆击概率)
  • 安全(随机密码,证书)
  • 测试(白盒测试)

随机数生成器的类型

  • 物理模型 (掷骰子,掷硬币,白噪声。。。)
  • 数学模型

随机数的生成方法

物理的方法是根据实验结果通过hash 函数 对应成数据流,在计算机编程中可能不会用到那么复杂的随机数生成器。这时可以运用现成的随机发生器来模拟物理生成器。比如说socket发送过来的时间,键盘,鼠标的事件,当前占用内存最大的pid值。都是用来产生随机数的好的素材。
数学模型是通过公用的公式:X(n+1) = (a * X(n) + c) % m。对应参数值:

模m, m > 0

系数a, 0 < a < m

增量c, 0 <= c < m

原始值(种子) 0 <= X(0) < m

其中参数c, m, a比较敏感,或者说直接影响了伪随机数产生的质量。

每个厂商对应都有自己的参数,如果对其它厂商的参数比较感兴趣的话可以看这里

随机种子

随机算法都是通用的,程序中遇到不同的问题,需要根据情况来决定提供什么样的随机种子。通过上面的公式我们知道如果提供相同的种子每次产生的随机序列是一样的。所以程序中常用的方法是用当前时间来做随机算法的种子。但是通过当前时间就一定能每次产生的随机数是不一样的吗?

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <ctime>  
  3.   
  4. int GetRandNum(int min, int max) {  
  5.     srand(time(NULL));  
  6.     return (min + rand() %(max - min +1));  
  7. }  
  8. int main() {  
  9.     std::cout<<"the num is:";  
  10.     for(int i = 0; i < 10; ++i) {  
  11.         std::cout<<GetRandNum(0, 10)<<"\t";  
  12.     }  
  13.     std::cout<<"\n";  
  14. }  


为什么结果都是一样的呢,这就是前面说的种子一样的话每次产生的随机数是一样的,因为time(NULL) 只能精确到秒,所以在一秒内程序很轻松执行完。遇到这种问题如何解决呢,当然用精度更高的纳秒是一种解决办法,也可以用当前的随机数做为下次随机的种子也是一种好的方式。

常用随机数算法

boost库自己提供的随机数发生器:

[cpp] view plaincopy
  1. #include <boost/random/mersenne_twister.hpp>  
  2. #include <boost/random/uniform_int_distribution.hpp>  
  3.   
  4. int main() {  
  5.     boost::random::mt19937 rng;  
  6.     boost::random::uniform_int_distribution<int> index_dis(0, 10);  
  7.     std::cout<<"the num is:";  
  8.     for(int i =0; i < 10; ++i) {  
  9.         std::cout<<index_dis(rng)<<"\t";  
  10.     }  
  11.     std::cout<<"\n";  
  12.     return 0;  

}


自己实现的随机发生器:
[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <ctime>  
  3.   
  4. static int seed = time(NULL);  
  5. int GetRandNum(int min, int max) {  
  6.     srand(seed);  
  7.     seed = rand();  
  8.     return (min + rand() %(max - min +1));  
  9. }  
  10. int main() {  
  11.     std::cout<<"the num is:";  
  12.     for(int i = 0; i < 10; ++i) {  
  13.         std::cout<<GetRandNum(1, 10)<<"\t";  
  14.     }  
  15.     std::cout<<"\n";  
  16. }  



facebook的随机种子:

[cpp] view plaincopy
  1. #include "folly/Random.h"  
  2.   
  3. #include <unistd.h>  
  4. #include <sys/time.h>  
  5.   
  6. namespace folly {  
  7.   
  8. uint32_t randomNumberSeed() {  
  9.   struct timeval tv;  
  10.   gettimeofday(&tv, NULL);  
  11.   const uint32_t kPrime1 = 61631;  
  12.   const uint32_t kPrime2 = 64997;  
  13.   const uint32_t kPrime3 = 111857;  
  14.   return kPrime1 * static_cast<uint32_t>(getpid())  
  15.        + kPrime2 * static_cast<uint32_t>(tv.tv_sec)  
  16.        + kPrime3 * static_cast<uint32_t>(tv.tv_usec);  
  17. }  
  18.   
  19. }  

随机数生成器效率

通过生成10,000,000随机数来测试效率和随机数的分布。

boost的随机发生器

[cpp] view plaincopy
  1. #include <boost/random/mersenne_twister.hpp>  
  2. #include <boost/random/discrete_distribution.hpp>  
  3. #include <iostream>  
  4. #include <map>  
  5. #include <ctime>  
  6. #include <sys/time.h>  
  7. #define TEST_COUNT 10000000  
  8. int main() {  
  9.     boost::mt19937 gen;  
  10.     double probabilities[] ={0.1, 0.12, 0.2, 0.26, 0.32};  
  11.     boost::random::discrete_distribution<> dist(probabilities);  
  12.   
  13.     struct timeval tim;  
  14.     gettimeofday(&tim, NULL);  
  15.     std::cout<<"start time:"<<tim.tv_sec<<"the micro sec is:"<<tim.tv_usec<<"\n";  
  16.     std::map<floatint> statis_map;  
  17.     for(int i = 0; i < TEST_COUNT; ++i) {  
  18.         statis_map[probabilities[dist(gen)]]++;  
  19.     }  
  20.     gettimeofday(&tim, NULL);  
  21.     std::cout<<"end time:"<<tim.tv_sec<<"the micro sec is:"<<tim.tv_usec<<"\n";  
  22.   
  23.     for(std::map<floatint>::iterator iter = statis_map.begin(); iter != statis_map.end(); ++iter) {  
  24.         std::cout<<"the per:"<<iter->first<<"\tresult per:"<<(float)iter->second/TEST_COUNT<<"\n";  
  25.     }  
  26.     return 0;  
  27. }  

结果为:


自制随机发生器

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <cmath>  
  3. #include <ctime>  
  4. #include <map>  
  5. #include <sys/time.h>  
  6. using namespace std;  
  7. #define TEST_COUNT 10000000  
  8. static int s_rand = time(NULL);  
  9. float RandomFloat()  
  10. {     
  11.     srand(s_rand);  
  12.     int i =  rand();  
  13.     s_rand = i;  
  14.     return (float)(i%100)/100;  
  15. }  
  16.   
  17. int main()   
  18. {  
  19.     float per_array[] ={0.1, 0.12, 0.2, 0.26, 0.32};  
  20.   
  21.     timeval tim;  
  22.     gettimeofday(&tim, NULL);  
  23.       
  24.     cout<<"start time:"<<tim.tv_sec<<"the micro sec is:"<<tim.tv_usec<<"\n";  
  25.     map<floatint> per_map;       
  26.     for(int i = 0; i < TEST_COUNT; ++i) {  
  27.         float frand = RandomFloat();  
  28.         float min = 0;  
  29.         float max = 1.0f;  
  30.         for(int i =0; i < 5; ++i){  
  31.             min = max - per_array[i];  
  32.             if(frand >= min){  
  33.                 per_map[per_array[i]]++;   
  34.                 break;  
  35.             }  
  36.             max = min;  
  37.         }  
  38.     }  
  39.       
  40.     gettimeofday(&tim, NULL);  
  41.     cout<<"end time:"<<tim.tv_sec<<"the micro sec is:"<<tim.tv_usec<<"\n";  
  42.     map<floatint>::iterator iter = per_map.begin();   
  43.     for(;iter != per_map.end(); ++iter) {  
  44.         float per_count = (float)iter->second;  
  45.         cout<<"the per:"<<iter->first<<"\tresult per:"<<per_count/TEST_COUNT<<endl;  
  46.     }  
  47.     return 0;  
  48. }  

结果为:


通过分析得知,两个随机发生器的概率分布,基本上和给出的概率非常吻合,运算速度的话,自制的随机发生器比boost几乎快一倍。经常听到很多人不要重新制造轮子,吐槽c++的程序员喜欢自造轮子。确实已经存在的东西没必要再去重写一边,因为那是浪费时间。但是并不代表说不会造轮子,假如都不知道如何造,又如何分辨轮子的好坏,哪些程序岂不要考蒙来写。那写出来的代码质量也是按随机概率分布的。。。。。

有意思的随机程序

boost生成随机密码

[cpp] view plaincopy
  1. #include <boost/random/mersenne_twister.hpp>  
  2. #include <boost/random/uniform_int_distribution.hpp>  
  3.   
  4. int main() {  
  5.     std::string chars(  
  6.         "abcdefghijklmnopqrstuvwxyz"  
  7.         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
  8.         "1234567890"  
  9.         "!@#$%^&*()"  
  10.         "`~-_=+[{]{\\|;:'\",<.>/? ");  
  11.     boost::random::mt19937 rng;  
  12.     boost::random::uniform_int_distribution<int> index_dist(0, chars.size() - 1);  
  13.     std::cout<<"You pwd is:\t";  
  14.     for(int i = 0; i < 8; ++i) {  
  15.         std::cout << chars[index_dist(rng)];  
  16.     }  
  17.     std::cout << std::endl;  
  18. }  

结果:


自制随机发生器生成密码

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <ctime>  
  4. using namespace std;  
  5.   
  6. static int seed = time(NULL);  
  7. int RandomRange(int min, int max) {  
  8.     srand(seed);  
  9.     seed = rand();  
  10.     return (min + (rand())%(max-min));  
  11. }  
  12. char RollChar() {  
  13.      std::string chars(  
  14.         "abcdefghijklmnopqrstuvwxyz"  
  15.         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
  16.         "1234567890"  
  17.         "!@#$%^&*()"  
  18.         "`~-_=+[{]{\\|;:'\",<.>/? ");  
  19.     char ch = chars[RandomRange(0, chars.size())];  
  20.     return ch;  
  21. }  
  22.   
  23. string RollString(int min, int max) {  
  24.     int str_len = RandomRange(min, max);  
  25.   
  26.     string str(str_len, '0');  
  27.     for(int i = 0; i < str_len; ++i) {  
  28.         str[i] = RollChar();  
  29.     }  
  30.     return str;  
  31.   
  32. }  
  33.   
  34. int main() {  
  35.     int count, min_length, max_length;  
  36.     cout<<"the count you want to:\n";  
  37.     cin>>count;  
  38.     cout<<"the min, and max username length:\n";  
  39.     cin>>min_length>>max_length;  
  40.     if(min_length > max_length || min_length < 0) {  
  41.         cout<<"you stupid boy!!!\n";  
  42.         return 1;  
  43.     }  
  44.   
  45.     for(int i = 0; i < count; ++i) {  
  46.         cout<<"the user name is:\t"<<RollString(min_length, max_length)<<"\tThe pwd:\t"<<RollString(8,10)<<endl;  
  47.     }  
  48.     return 0;  
  49. }  

结果:


可以根据这个算法写个生成账号密码的软件,专门来管理自己日常的密码,可以生成变态的用户名密码。

引用参考:

http://www.boost.org/doc/libs/1_50_0/doc/html/boost_random.html

http://en.wikipedia.org/wiki/Random_number_generation

http://blog.csdn.net/hackmind/article/details/6388044


0 0
原创粉丝点击