www.pudn.com > Grass.rar > Rand.cpp


// Rand.cpp: implementation of the CRand class. 
// 
////////////////////////////////////////////////////////////////////// 
 
#include "stdafx.h" 
#include "FGrass.h" 
#include "Rand.h" 
 
#include 
#include 
 
#ifdef _DEBUG 
#undef THIS_FILE 
static char THIS_FILE[]=__FILE__; 
#define new DEBUG_NEW 
#endif 
 
#define _rand_table_size 101 
#define _rand_init_seed 3030303l 
 
static int first_time=1; 
static int need_newvars = 1; 
static int last_rand_int = _rand_init_seed; 
static RandType rand_table[_rand_table_size]; 
static RandType last_rand; 
 
void _srand(unsigned long iseed) 
{ 
	srand(iseed); 
	for(int i=0;i<_rand_table_size;i++) 
		rand_table[i]=rand()/(RAND_MAX+RandType(1)); 
	last_rand=(last_rand_int=rand())/(RAND_MAX+RandType(1)); 
	first_time=0; 
	need_newvars = 1; 
} 
 
RandType _rand(void) 
{ 
	int index; 
	if(first_time) 
		_srand(_rand_init_seed); 
	index=unsigned int(_rand_table_size*last_rand); 
	last_rand=rand_table[index]; 
	rand_table[index]=(last_rand_int=rand())/(RAND_MAX+RandType(1)); 
	return last_rand; 
} 
 
RandType _randBiUniform(void) 
{ 
	RandType x; 
 
	x = _rand(); 
	if (_rand() < 0.5f) x *= -1; 
	return x; 
} 
 
RandType _randExponential(void) 
{ 
	RandType x; 
 
	x = _rand(); 
	return RandType(-log(x)); 
} 
 
RandType _randBiExponential(void) 
{ 
	RandType x; 
 
	x = _randExponential(); 
	if (_rand() < 0.5f) x *= -1; 
 
	return x; 
} 
 
RandType _randgauss(void) 
{  
	static RandType factor,v1,v2; 
	RandType result; 
	 
	if(need_newvars) 
	{  
		RandType r=RandType(1.1); 
		while(r>=1||r==0) 
		{  
			v1=2*_rand()-1; 
			v2=2*_rand()-1; 
			r=v1*v1+v2*v2; 
		} 
		need_newvars=0; 
		factor=RandType(sqrt(-2*log(r)/r)); 
		result=v1*factor; 
	} 
	else 
	{  
		need_newvars=1; 
		result=v2*factor; 
	} 
	return result; 
} 
 
int _randGetSeed(void) 
{ 
	return last_rand_int; 
} 
 
void CRandBase::setseed(long new_seed) 
{  
	m_seed=new_seed; 
//	_srand(m_seed); 
} 
 
void CRandBase::setCurSeed(long new_seed) 
{  
	m_seed=new_seed; 
	_srand(m_seed); 
} 
 
void CRandBase::setCurSeed() 
{  
	_srand(m_seed); 
} 
 
RandType CRandUniform::next(void) 
{  
//	return (_rand()*2*m_stdev+m_mean-m_stdev); 
//	return (_rand()*(m_stdev-m_mean)+m_mean); 
	setseed(_randGetSeed()); 
	return (2*(_rand()-0.5f)*m_stdev+m_mean); 
} 
 
RandType CRandGauss::next(void) 
{  
	setseed(_randGetSeed()); 
	return (_randgauss()*m_stdev+m_mean); 
} 
 
void CRandExponential::CalcRange() 
{ 
	m_min=RandType(exp(-m_stdev-m_mean)); 
	m_max=RandType(exp( m_stdev-m_mean)); 
} 
 
RandType CRandExponential::next(void) 
{  
	setseed(_randGetSeed()); 
	RandType x; 
 
	x = _rand(); 
	return RandType(-log( x*(m_max-m_min) + m_min )); 
//	return (_randExponential()*m_stdev+m_mean); 
}