random.cpp [C++]
// Random
//
// 2012.03.01 coded by 心如
#include <iostream>
#include <ctime>
using namespace std;
const Mxn = 1000;
// 乱数
class Random{
int sd1, sd2, sd3;
void SetSeed(int);
public:
Random(){ SetSeed( time(NULL)); }
Random(int seed){ SetSeed( seed); }
float rand_f();
// 0以上n未満の整数の乱数
int rand_i(int n){ return (int )(rand_f() * n); }
};
// 乱数の初期値の設定
void Random::SetSeed(int seed){
sd1 = seed % 30269 + 1;
sd2 = seed % 30307 + 1;
sd3 = seed % 30323 + 1;
}
// 実数(0以上1.0未満)の一様乱数の発生
float Random::rand_f(){
float f;
sd1 = (sd1 % 177) * 171 - (sd1 / 177) * 2;
if(sd1 < 0) sd1 += 30269;
sd2 = (sd2 % 176) * 172 - (sd2 / 176) * 35;
if(sd2 < 0) sd2 += 30307;
sd3 = (sd3 % 178) * 170 - (sd3 / 178) * 63;
if(sd3 < 0) sd3 += 30323;
f = sd1 / 30269.0 + sd2 / 30307.0 + sd3 / 30323.0;
while( f >= 1.0){
f -= 1.0;
}
return f;
}
int main(){
Random a((int)time(NULL));
for(int i = 0; i < 320; i++){
printf("%4d,", a.rand_i(Mxn));
}
}
─────
コメント 0