zoukankan      html  css  js  c++  java
  • 一个简单的随机数生成算法实现(C++)

    #ifndef EASYRANDOM_INCLUDED
    #define    EASYRANDOM_INCLUDED

    static const int A = 48271;
    static const int M = 2147483647;
    static const int Q = M/A ;
    static const int R = M%A ;

    class Random
    {
    public :
        
    explicit Random(int initialVal=1);

        
    int RandomInt();
        
    double Random0_1();
        
    int RandomInt(int low,int high);
    private :
        
    int state;
    }
    ;

    Random::Random(
    int initialVal)
    {
        
    if(initialVal < 0)
            initialVal 
    += M;
        
        state 
    = initialVal;
        
    if(state==0)
            state
    =1;
    }


    int Random::RandomInt()
    {
        
    int tmpState = A*( state % Q ) - R * (state / Q);

        
    if(tmpState > 0)
            state 
    = tmpState;
        
    else
            state 
    = tmpState + M;

        
    return state;
    }

    //生成0.0到1.0之间的随机小数
    double Random::Random0_1()
    {
        
    return (double)RandomInt()/M;
    }

    //生成low到high之间的随机整数
    int Random::RandomInt(int low, int high)
    {
        
    int range = high - low;
        
        
    return low+RandomInt()%range;
    }


    #endif

    这些数的生成依赖于算法,不能算是真正的随机数,只能算是伪随机数。本例中的算法详情google 线性同余生成器。

    ps.

    没有关键的C代码插入方式,用C#的顶下先 

  • 相关阅读:
    新手silverlight练习五子棋( 二 )
    VS注释模板工具
    NET简介
    MS Sql server 总结(命令恢复)
    Highcharts入门(一)
    jqGrid入门(1)
    WIN7常见问题汇总
    log4net入门
    DLL管理工具
    C++回顾1 简介
  • 原文地址:https://www.cnblogs.com/zelos/p/3402884.html
Copyright © 2011-2022 走看看