示例#1
0
double gasdev(int *idum){

  static int   iset = 0;
  static double gset;
  double        fac, rsq, v1, v2;

  if(iset == 0){
    do{
      v1 = 2.0 * ran2(idum) - 1.0;
      v2 = 2.0 * ran2(idum) - 1.0;
      rsq = v1*v1+v2*v2;

    } while( rsq >= 1.0 || rsq == 0.0);

    fac = sqrt(-2.0*log(rsq)/rsq);
    gset = v1*fac;
    iset = 1;

    return v2*fac;
  }

  else{

    iset = 0;

    return gset;
  }

}
示例#2
0
int poissrnd(double xm)
{
	static double sq, alxm, g, oldm=(-1.0);
	double em,t,y;
	
	if (xm < 12.0) { 
		if (xm != oldm) {
			oldm=xm;
			g=exp(-xm); 
		}
		em = -1;
		t=1.0;
		do {
			++em;
			t *= ran2();
		} while (t > g);
	} else { 
		if (xm != oldm) { 
			oldm=xm;
			sq=sqrt(2.0*xm);
			alxm=log(xm);
			g = xm*alxm - gammln(xm + 1.0);
		}
		do {
			do { 
				y=tan(PI * ran2());
				em=sq*y+xm; 
			} while (em < 0.0); 
			em=floor(em); 
			t=0.9*(1.0+y*y)*exp(em*alxm-gammln(em+1.0)-g);
		} while (ran2() > t);
	}
	return (int)em;
}
示例#3
0
文件: CState.cpp 项目: FSund/FYS4460
void CState::randnVelocity(double mean, double sigma_v, long *seed)
{
    vec2 randomNormal, randomUniform;
    mat velocities(nAtoms, 3);
    rowvec3 momentum;
    double R;

    for (int i = 0; i < nAtoms; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // Box-Muller transform
            randomUniform << ran2(seed) << ran2(seed);
            R = sqrt(-2*log(randomUniform(0)));
            randomNormal(0) = R*cos(2*pi*randomUniform(1));
            velocities(i, j) = randomNormal(0)*sigma_v + mean;

            // unused random number... should probably use this one for something
            // randomNormal(1) = R*sin(2*pi*randomUniform(1))*sigma_v + mean;
        }
    }

    momentum = sum(velocities)/nAtoms; // finding the linear momentum of the system
    for (int i = 0; i < nAtoms; i++)
    {
        velocities.row(i) -= momentum; // removing initial linear momentum from the system
    }

    // sending the generated velocities to the atoms
    for (int i = 0; i < nAtoms; i++)
    {
        atoms[i]->setVelocity(velocities.row(i).t());
    }
}
示例#4
0
// Normal Distrubted random number generator
// From Numerical Recipes in C, Press et al. 1988
// Returns a normally distributed random number with zero mean and unit variance
double normrnd(void)
{
	extern long *idum;
	static int iset=0;
	static double gset;
	double fac, r, v1, v2;

	if (iset == 0)
	{
		do
		{
			v1 = 2.0 * ran2() - 1.0;
			v2 = 2.0 * ran2() - 1.0;
			r = v1 * v1 + v2 * v2;
		} while (r >= 1.0);
		
		fac = sqrt(-2.0*log(r) / r);
		gset = v1 * fac;
		iset = 1;
		return v2*fac;
	} 
	else
	{
		iset = 0;
		return gset;
	}
}
示例#5
0
double powlaw(double r0, double r1, double b, long *idum)
{
  double r, k, x;
  double ran2();

  if(b != -1.0){

    if(b < -1.0 && (r0 == 0.0 || r1 == 0.0)){
      fprintf(stderr, "bad powlaw values %lf %lf %lf\n", r0, r1, b);
      exit(-1);
    }

    k = (b+1.0)/(pow(r1, b+1.0)-pow(r0, b+1.0));
    r = ran2(idum);
    x = pow((b+1.0)/k*r + pow(r0, b+1.0), 1.0/(b+1.0));

  }else{
    
    if(r0 <= 0.0 || r1 <= 0.0){
      fprintf(stderr, "bad powlaw values %lf %lf %lf\n", r0, r1, b);
      exit(-1);
    }
    
    k = 1.0/(log(r1) - log(r0));
    r = ran2(idum);
    x = exp(r/k);
    
  }
  return(x);
}
/**
 * Simulates the step of a squirrel. You can call this with the arguments (0,0,&x,&y,&state)
 * to determine a random initial starting point.
 * x_new and y_new are the new x and y coordinates, state is used in the random number
 * generator and is also modified.
 * x_new can point to x, and y_new can point to y
 */
void squirrelStep(float x, float y, float* x_new, float* y_new, long * state){

    float diff=ran2(state);
    *x_new=(x+diff)-(int)(x+diff);

    diff=ran2(state);
    *y_new=(y+diff)-(int)(y+diff);
}
示例#7
0
double VMCSolver::gaussianDeviate(long *seed)
{
    double R, randomNormal;
    // Box-Muller transform
    R = sqrt(-2.0*log(ran2(seed)));
    randomNormal = R*cos(2.0*(pi) *ran2(seed));
    return randomNormal;
}
示例#8
0
int getrandomnp(int istep, int niter){
	if(istep < niter/10) {
		return (int)(3000+5000*(ran2(&iseed)));
	}
	else {
		return (int)(100*(ran2(&iseed)));
	}
}
示例#9
0
/*! \fn double Normal(long int *idum)
 *  \brief Normal distribution random number generator */
double Normal(long int *idum)
{
  double Y,X1,X2;

  X1 = ran2(idum);
  X2 = ran2(idum);

  Y = sqrt(-2.0*log(X1+TINY_NUMBER))*cos(2*PI*X2);

  return Y;
}
示例#10
0
static void pspect(ath_fft_data *ampl)
{
  int i,j,k;
  double q1,q2,q3;

  /* set random amplitudes with gaussian deviation */
  for (k=0; k<nx3; k++) {
    for (j=0; j<nx2; j++) {
      for (i=0; i<nx1; i++) {
        q1 = ran2(&rseed);
        q2 = ran2(&rseed);
        q3 = sqrt(-2.0*log(q1+1.0e-20))*cos(2.0*PI*q2);
        q1 = ran2(&rseed);
        ampl[OFST(i,j,k)][0] = q3*cos(2.0*PI*q1);
        ampl[OFST(i,j,k)][1] = q3*sin(2.0*PI*q1);
      }
    }
  }

  /* set power spectrum
   *   ispect=1: power law - original form
   *   ispect=2: form from Gammie&Ostriker
   */
  for (k=0; k<nx3; k++) {
    for (j=0; j<nx2; j++) {
      for (i=0; i<nx1; i++) {
        /* compute k/dkx */
        q3 = KWVM(i,j,k);
        if ((q3 > klow) && (q3 < khigh)) {
          q3 *= dkx; /* multiply by 2 pi/L */
          if (ispect == 1) {
            /* decreasing power law */
            ampl[OFST(i,j,k)][0] /= pow(q3,(expo+2.0)/2.0);
            ampl[OFST(i,j,k)][1] /= pow(q3,(expo+2.0)/2.0);
          } else if (ispect == 2) {
            /* G&O form */
            ampl[OFST(i,j,k)][0] *= pow(q3,3.0)*exp(-4.0*q3/kpeak);
            ampl[OFST(i,j,k)][1] *= pow(q3,3.0)*exp(-4.0*q3/kpeak);
          }
        } else {
          /* introduce cut-offs at klow and khigh */
          ampl[OFST(i,j,k)][0] = 0.0;
          ampl[OFST(i,j,k)][1] = 0.0;
        }
      }
    }
  }
  ampl[0][0] = 0.0;
  ampl[0][1] = 0.0;

  return;
}
示例#11
0
double gasdev (void)
{	static double f=0,rsq=1,v1=1,v2=1;
	static int res=0;
	if (res)
	{	res=0; return v2*f;
	}
	do
	{	v1=2.0*ran2()-1.0;
		v2=2.0*ran2()-1.0;
		rsq=v1*v1+v2*v2;
	} while (rsq >= 1.0 || rsq <= 0.00001);
	f=sqrt(-2.0*log(rsq)/rsq);
	res=1;
	return v1*f;
}
示例#12
0
double ran2(double min, double max)
{
	double r = ran2();
	r *= (max - min);
	r += min;
	return r;
}
示例#13
0
文件: CState.cpp 项目: FSund/FYS4460
void CState::randuVelocity(double mean, double vmax, long *seed)
{
    mat velocities(nAtoms, 3);
    rowvec momentum(nAtoms);

    // generating random, uniform velocities
    for (int i = 0 ; i < nAtoms; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            velocities(i, j) = (ran2(seed)-0.5)*vmax + mean;
        }
    }
    // removing any linear momentum from the system
    momentum = sum(velocities)/nAtoms;
    for(int i = 0; i < nAtoms; i++)
    {
        velocities.row(i) -= momentum;
    }
    // sending the velocities to the atoms
    for (int i = 0; i < nAtoms; i++)
    {
        atoms[i]->setVelocity(velocities.row(i).t());
    }
}
示例#14
0
int ran2(int min, int max)
{
	double r = ran2();
	r *= (double)(max - min);
	r += min;
	return (int)r;
}
示例#15
0
void SolverMCBF::runCycle()
{
    // loop over Monte Carlo cycles
    for (int cycle = 0; cycle < nCycles+nThermalize; cycle++)
    {
        // New position to test
        for (int i = 0; i < nParticles; i++)
        {
            for (int j = 0; j < nDimensions; j++)
            {
                rNew(i,j) = rOld(i,j) + stepLength*(ran2(&idum) - 0.5);
            }

            wf->updatePositionAndCurrentParticle(rNew, i);
            ratio = wf->getRatio(); // squared in Wavefunction

            // Check for step acceptance (if yes, update position, if no, reset position)
            if (ran2(&idum) <= ratio)
            {
                rOld.row(i) = rNew.row(i);
                wf->acceptMove();
                if (cycle > nThermalize) nAccepted++;
            }
            else
            {
                rNew.row(i) = rOld.row(i);
                wf->rejectMove();
            }
        }
        if (cycle >= nThermalize)
        {
            deltaE = localEnergy->evaluate(rNew, wf);

            if (blocking)
                logger->log(deltaE);

            energySum += deltaE;
            energySquaredSum += deltaE*deltaE;
            if (minimizing)
            {
                tempVariationalGradient = wf->variationalDerivatives();
                variationalGradientSum += tempVariationalGradient;
                variationalGradientESum += tempVariationalGradient*deltaE;
            }
        }
    }
}
示例#16
0
double Diffusion::call_RNG() {
#ifdef RNG_ZIG
    return DRan_MWC8222();
#endif
#ifdef RNG_NUMREC
    return ran2(&random_seed);
#endif
}
示例#17
0
int bnlrnd(double pp, int n)
{
	int j;
	static int nold=(-1);
	double am,em,g,angle,p,bnl,sq,t,y;
	static double pold=(-1.0),pc,plog,pclog,en,oldg;
	p=(pp <= 0.5 ? pp : 1.0-pp);
	am=n*p;		//This is the mean of the deviate to be produced.
	if (n < 25) { 
		bnl = 0.0;
		for (j=1;j<=n;j++)
			if (ran2() < p) ++bnl;
	} else if (am < 1.0) { 
		g=exp(-am);
		t=1.0;
		for (j=0;j<=n;j++) {
			t *= ran2();
			if (t < g) break;
		}
		bnl=(j <= n ? j : n);
	} else {
		if (n != nold) { 
			en=n; 
			oldg=gammln(en+1.0);
			nold=n;
		} if (p != pold) { 
			pc=1.0-p; 
			plog=log(p);
			pclog=log(pc);
			pold=p;
		}
		sq=sqrt(2.0*am*pc); 
		do {
			do {
				angle=PI*ran2();
				y=tan(angle);
				em=sq*y+am;
			} while (em < 0.0 || em >= (en+1.0)); 
			em=floor(em); 
			t=1.2*sq*(1.0+y*y)*exp(oldg-gammln(em+1.0)-gammln(en-em+1.0)+em*plog+(en-em)*pclog);
		} while (ran2() > t); bnl=em; 
	}
	if (p != pp) bnl=n-bnl; 
	return (int)bnl;
}
示例#18
0
double ran4(bool t, long s) {
    double r = 0;
    static long seed_ = 1;
    if (t)
        r = ran2(&seed_);
    else
        seed_ = s;
    return r;
}
示例#19
0
int willGiveBirth(float avg_pop, long * state){
  
    float tmp;

    tmp=avg_pop/2000.0;

    return(ran2(state)<(atan(tmp*tmp)/(4*tmp)));

}
示例#20
0
void frogHop(float x, float y, float* x_new, float* y_new, long * state){

    /* 
     * You can also use frogHop (0,0,x_start,y_start,idum) to get a random
     * starting position for a frog.
     */

  
    float diff;

    diff=ran2(state); /* don't worry that diff is always >0 this is
                      * dealt with by the periodic BCs */
  
    *x_new=(x+diff)-(int)(x+diff);

    diff=ran2(state);

    *y_new=(y+diff)-(int)(y+diff);

  
}
// random numbers with gaussian distribution
double gaussian_deviate(long * idum)
{
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
if ( idum < 0) iset =0;
if (iset == 0) {
do {
v1 = 2.*ran2(idum) -1.0;
v2 = 2.*ran2(idum) -1.0;
rsq = v1*v1+v2*v2;

} while (rsq >= 1.0 || rsq == 0.);
fac = sqrt(-2.*log(rsq)/rsq);
gset = v1*fac;
iset = 1;
return v2*fac;
} else {
iset =0;
return gset;
}
} // end function for gaussian deviates
示例#22
0
// Returns random numbers distributed as a gamma distribution
// From Devroye 1986
double gamrnd(double ia, double ib)
{
	double b, c, d, u, v, w, x, y, z;
	int accept;
	double ret = 0;

	if (ia == 1.0)
	{
		// gamma is exponetial (Devroye pg 405)
		ret = -ib * log(ran2());
	}
	else if ((ia < 1) && (ia > 0))
	{
		c = 1 / ia;
		d = 1 / (1 - ia);
		accept = 0;
		do 
		{
			u = ran2();
			v = ran2();
			x = pow(u, c);
			y = pow(v, d);
			z = x + y;
			if (z <= 1.0)
				accept = 1;
		} while (accept != 1);

		ret = -ib * log(ran2()) * x / z;
	}
	else if (ia > 1)
	{
		b = ia - 1;
		c = 3.0 * ia - 0.75;
		accept = 0;
		do
		{
			u = ran2();
			v = ran2();
			w = u * (1 - u);
			y = (u - 0.5) * sqrt(c / w);
			x = b + y;
			if (x >= 0.0)
			{
				z = 64.0 * pow(w, 3) * pow(v, 2);
				if (z <= (1 - 2 * y * y / x))
				{ accept = 1; }
				else
				{	
					if (log(z) <= (2 * (b * log(x / b) - y)))
					{ accept = 1; }
				}
			}
		} while (accept != 1);

			ret = ib * x;
	}
	return ret;
}
示例#23
0
void permute(uint n, uint *indx) {
  uint i,j,k;
  for (i=1; i<= n; i++) {
    indx[i] = 0;
  }
  for (i=n; i > 0; i--) {
    k = (uint) ceil(ran2(_seed2Ptr)*(i*1.0));
    for (j = 1; k > 0; j++) {
      if (indx[j] == 0) {
        k--;
      }
    }
    indx[j-1] = i;
  }
}
示例#24
0
Node *randomizeMembership(Node    *parent, 
                          double **predictor, 
                          uint     individual, 
                          uint     splitParameter) {
  char daughterFlag;
  char randomSplitFlag;
  Node *result;
  result = parent;
  if (((parent -> left) != NULL) && ((parent -> right) != NULL)) {
    randomSplitFlag = FALSE;
    if (splitParameter > 0) {
      if ((parent -> splitParameter) == splitParameter) {
        randomSplitFlag = TRUE;
      }
    }
    else {
      if(_importanceFlag[parent -> splitParameter] == TRUE) {
        randomSplitFlag = TRUE;
      }
    }
    if(randomSplitFlag == TRUE) {
      if (ran2(_seed2Ptr) <= 0.5) {
        result = randomizeMembership(parent ->  left, predictor, individual, splitParameter);
      }
      else {
        result = randomizeMembership(parent -> right, predictor, individual, splitParameter);
      }
    }
    else {
      daughterFlag = RIGHT;
      if (strcmp(_xType[parent -> splitParameter], "C") == 0) {
        daughterFlag = splitOnFactor((uint) predictor[parent -> splitParameter][individual], parent -> splitValueFactPtr);
      }
      else {
        if (predictor[parent -> splitParameter][individual] <= (parent -> splitValueCont)) {
          daughterFlag = LEFT;
        }
      }
      if (daughterFlag == LEFT) {
        result = randomizeMembership(parent ->  left, predictor, individual, splitParameter);
      }
      else {
        result = randomizeMembership(parent -> right, predictor, individual, splitParameter);
      }
    }
  }
  return result;
}
示例#25
0
void initialiseRNG(long *seed) {

    /* 
     * Call this **once** at the start of your program **on each process**
     * The input value should be **negative**, **non-zero**, and
     *  **different on every process**
     * You could seed with the value -1-rank where rank
     *  is your MPI rank
     * 
     * ran2 is a flawed RNG and must be used with particular care in parallel
     * however it is perfectly sufficient for this coursework
     * 
     *  printf("Initialising with %d",*idum);
     */
    ran2(seed);
}
示例#26
0
void mrandom (header *hd)
{	header *st=hd,*result;
	double *m;
	int r,c;
	LONG k,n;
	hd=getvalue(hd); if (error) return;
	if (hd->type!=s_matrix || dimsof(hd)->r!=1 || dimsof(hd)->c!=2
		|| *(m=matrixof(hd))<0 || *m>=INT_MAX
		|| *(m+1)<0 || *(m+1)>INT_MAX)
		wrong_arg_in("random");
	r=(int)*m;
	c=(int)*(m+1);
	result=new_matrix(r,c,""); if (error) return;
	m=matrixof(result);
	n=(LONG)c*r;
	for (k=0; k<n; k++) *m++=(double)ran2();
	moveresult(st,result);
}
示例#27
0
文件: CState.cpp 项目: FSund/FYS4460
void CState::remove_half_the_atoms()
{
    cout << "CState::remove_half_the_atoms" << endl;
    cout << "Old nAtoms = " << nAtoms << endl;
    cout << "Old nMovingAtoms = " << nMovingAtoms << endl;

    long idum = -1;
    for (int i = (nAtoms-1); i >= 0; i--)
    {
        if (!atoms[i]->matrixAtom && ran2(&idum) < 0.5)
        {
            delete atoms[i];
            atoms.erase(atoms.begin() + i);
        }
    }
    nAtoms = atoms.size();

    movingAtoms.clear();
    nMovingAtoms = 0;
    for (int i = 0; i < nAtoms; i++)
    {
        if (!atoms[i]->matrixAtom)
        {
            movingAtoms.push_back(atoms[i]);
            nMovingAtoms++;
        }
    }
    if (movingAtoms.size() != nMovingAtoms)  cout << "! Wrong number of moving atoms after removing half!" << endl;

    for (int i = 0; i < nBoxes; i++)
    {
        boxes[i]->flush();
    }
    fillBoxes();

    ////
    cout << "New nAtoms = " << nAtoms << endl;
    cout << "New nMovingAtoms = " << nMovingAtoms << endl;
    ////

    cout << "Exiting CState::remove_half_the_atoms" << endl << endl;
}
示例#28
0
void init_random()
{
	double ns=0.1, area;
	long i, j;
	
	printf("Input area percentage ");
	scanf("%lg",&area);
	
	printf("Input random seed ");
    scanf("%ld",&seed);

	allocate_memory();
	
	for (i=1; i<=num_of_meshpoint_theta-1; i++){
		for (j=1; j<=2*num_of_meshpoint_phi; j++){
			phi[i][j] = (2*area-1)+ns*(1-2*ran2(&seed));
            //printf("Valori seed (%ld,%ld) %f\n",i,j,phi[i][j]);
		}
	}
}
示例#29
0
void mshuffle (header *hd)
{  header *st=hd,*result;
	double *m,*mr,x;
	int i,j,n;
	hd=getvalue(hd); if (error) return;
	if (hd->type!=s_matrix || dimsof(hd)->r!=1)
		wrong_arg_in("shuffle");
	n=dimsof(hd)->c;
	result=new_matrix(1,n,"");
	m=matrixof(hd); mr=matrixof(result);
	for (i=0; i<n; i++) *mr++=*m++;
	mr=matrixof(result);
	for (i=n-1; i>0; i--)
	{	j=(int)floor(ran2()*(i+1));
		if (i!=j)
		{	x=*(mr+i); *(mr+i)=*(mr+j); *(mr+j)=x;
		}
	}
	moveresult(st,result);

}
示例#30
0
double OneBodyDensity::McIntegrator(const vec &rActive, int id) {
    double stepLength = 6;
    double rho = 0;
    double waveFunc;
    mat r = zeros(nParticles, dim);
    r.row(0) = rActive.t();

    //--------------------------------------------------------------------------
    // Init of the particle that is at a constant r
    for (int i = 0; i < McSamples; i++) {
        // Generating new coordintes.
        for (int k = 1; k < nParticles; k++)
            for (int j = 0; j < dim; j++)
                r(k, j) = stepLength * (ran2(&idum) - 0.5);

        waveFunc = wf->evaluate(r);
        rho += waveFunc*waveFunc;
    }

    //--------------------------------------------------------------------------

    double tmp = rho;

    if (myRank != 0)
        MPI_Send(&rho, 1, MPI_DOUBLE, 0, id, MPI_COMM_WORLD);
        // Collecting data from the other processes.
    else {
        for (int i = 1; i < nNodes; i++) {
            MPI_Recv(&tmp, 1, MPI_DOUBLE, i, id, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            rho += tmp;
        }
    }

    rho /= nNodes;
    return rho;
}