'rand'에 해당되는 글 1건

  1. 2013.04.29 rand() 함수의 문제점을 극복한 알고리즘
프로그래밍/c++2013. 4. 29. 18:43

http://www.gamedevforever.com/114

 

rand() 함수보다 더 빠르고 난수 분포율도 더 나은 Well 알고리즘을 적용한 난수 발생기

-C++ 버전

namespace GRandom {
//
unsigned long state[16];
unsigned int index = 0;
//
void init(unsigned long seed) {
for (int i=0; i<16; ++i) {
state[i] = seed;
}
}
//
unsigned long get() {
unsigned long a, b, c, d;
a = state[index];
c = state[(index+13)&15];
b = a^c^(a<<16)^(c<<15);
c = state[(index+9)&15];
c ^= (c>>11);
a = state[index] = b^c;
d = a^((a<<5)&0xDA442D20UL);
index = (index+15)&15;
a = state[index];
state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
return
state[index];
}
//
int getInt(int nMin, int nMax) {
return (int)(get()%(nMax- nMin) ) + nMin;
}
}

 

 

- C# 버전

public class Well512
{
    static uint[] state = new uint[16];
    static uint index = 0;

    static Well512()
    {
        Random random = new Random((int)DateTime.Now.Ticks);

        for (int i = 0; i < 16; i++)
        {
            state[i] = (uint)random.Next();
        }
    }

    internal static uint Next(int minValue, int maxValue)
    {
        return (uint)((Next() % (maxValue - minValue)) + minValue);
    }

    public static uint Next(uint maxValue)
    {
        return Next() % maxValue;
    }

    public static uint Next()
    {
        uint a, b, c, d;

        a = state[index];
        c = state[(index + 13) & 15];
        b = a ^ c ^ (a << 16) ^ (c << 15);
        c = state[(index + 9) & 15];
        c ^= (c >> 11);
        a = state[index] = b ^ c;
        d = a ^ ((a << 5) & 0xda442d24U);
        index = (index + 15) & 15;
        a = state[index];
        state[index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);

        return state[index];
    }
}



Posted by GaePein