double vector_similarity(void) {

  double v1[4],v2[4],sum,dist;
  double *d;
  int numRandom;
  register int i,j;
 
  numRandom=100000;  
  d=alloc_double(numRandom);

  for (i=0; i<numRandom; i++) {
     for (j=0; j<4; j++) {
        v1[j]=genrand();
        v2[j]=genrand();
     }
     sum=0; for (j=0; j<4; j++) sum+=v1[j];
     if (sum!=0) { for (j=0; j<4; j++) v1[j]/=sum; }
     else        { for (j=0; j<4; j++) v1[j]=0.25; }

     sum=0; for (j=0; j<4; j++) sum+=v2[j];
     if (sum!=0) { for (j=0; j<4; j++) v2[j]/=sum; }
     else        { for (j=0; j<4; j++) v2[j]=0.25; }

     d[i]=0; for (j=0; j<4; j++) { d[i] +=fabs(v1[j]-v2[j]); } 
  }

  // sort in increasing order
  sort_double2(d,numRandom);
  dist=d[(int)(numRandom*SIMILARITY_ALPHA)];

  if (d) { free(d); d=NULL; }
  return (dist); 
}
Exemple #2
0
int main(void)
{
	printf( "Testing output and speed of mt19937int.c\n" );
	printf( "\nTest of random integer generation:\n" );
	sgenrand( 4357U );
	for( i = 0; i < 1000; ++i )
	{
        printf( "%10lu ", genrand() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of time to generate 300 million random integers:\n" );
	sgenrand( 4357U );
	startClock = clock();
	for( i = 0; i < 3e+8; ++i )
	{
		junk = genrand();
	}
	stopClock = clock();
	printf( "Time elapsed = " );
	printf( "%8.3f", (double)( stopClock - startClock ) / CLOCKS_PER_SEC );
	printf( " s\n" );
	
	return 0;
}
/*
 * Return a random number in the range 0..(n-1).
 */
unsigned int
DefaultRndNumGenerator::rnd_upto(const unsigned int n, const Filter *f, const std::string *where)
{
	static int g = 0;
	int h = g;
	if (h == 440)
		BREAK_NOP;   // for debugging
	unsigned int v = genrand() % n;
	unsigned INT64 local_depth = rand_depth_;
	rand_depth_++;
	//ofstream out("rnd.log", ios_base::app);
	//out << g++ << ": " << v << "(" << n << ")" << endl;

	if (f) {
		while (f->filter(v)) {
			// We could add numbers into sequence inside the previous filter.
			// If the previous filter failed, we need to roll back the rand_depth_ here.
			// This will also overwrite the value added in the map.
			rand_depth_ = local_depth+1;
			v = genrand() % n;
			/*out << g++ << ": " << v << "(" << n << ")" << endl;*/
		}
	}
	//out.close();
	if (where) {
	std::ostringstream ss;
		ss << *where << "->";
	trace_string_ += ss.str();
	}
	add_number(v, n, local_depth);
	return v;
}
Exemple #4
0
int main (int argc, char **argv)
{
  int i, n;
  int do_qsort;
  struct pair data[MAX], scratch[MAX];
  uint32_t sum, sum2;
  int iter;
  if (argc < 2) {
    exit(2);
  }
  n = atoi(argv[1]);
  if (n < 0) {
    do_qsort = 1;
    n = -n;
  } else {
    do_qsort = 0;
  }

  for (iter=0; iter<NITER; iter++) {
    for (i=0; i<n; i++) {
      data[i].foo = genrand(0);
      data[i].bar = genrand(0);
    }

    if (do_qsort) {
      qsort(data, n, sizeof(struct pair), pair_compare);
    } else {
      pair_sort(n, data, scratch);
    }
  }
  return 0;
}
Exemple #5
0
int plot(void *notused)
{
  plotter->PlotData(d);
  Point **points = d->GetPoints(0);
  while(!done)
  {
    for(int j=0; j<10 ; j++)
    {
      double err= 0.01*(randn());      
      int ind = (int)floor(genrand()*999)+1;
      for(int i=ind; i<1000 ; i++)
      {
	*points[i]->y = *points[i]->y + err;
      }
    }
    for(int j=0; j<100 ; j++)
    {
      double err= 0.01*(randn());      
      int ind = (int)floor(genrand()*999)+1;
      *points[ind]->y += + err;
    }

    SDL_Delay(15);
    plotter->PlotData(d);
  }

  return(0);
}
/* ========================================================================= */
void CLayerSnow::RenewSnowInfo(int nCount)
{
	int i, nTmp;
	PSTLAYERSNOW_SNOWINFO pInfo;

	DeleteSnowInfoAll ();

	for (i = 0; i < nCount; i ++) {
		pInfo = new STLAYERSNOW_SNOWINFO;

		nTmp = (genrand () % 3);
		pInfo->nState		= 0;
		pInfo->nLevel		= 100;
		pInfo->nSize		= 3 - nTmp;
		pInfo->nStartY		= genrand () % SCRSIZEY;
		pInfo->nEndY		= pInfo->nStartY + (SCRSIZEY - (genrand () % (SCRSIZEY / 3 * (nTmp + 1)))) + 32;
		pInfo->x			= (genrand () % SCRSIZEX) + 32;
		pInfo->y			= pInfo->nStartY;
		pInfo->dwStartWait	= genrand () % 3000;
		pInfo->dwWait		= 50 + nTmp * 50;
		pInfo->dwLastProc	= timeGetTime ();

		m_aSnowInfo.Add (pInfo);
	}
}
Exemple #7
0
bool_t treasures(struct pos plpos) {
    extern int rows, cols;
    static struct pos trpos;
    static int trcount;
    static int oldrows, oldcols;

    if (!trcount) {                 /* New treasure needed */
        trpos.row = genrand(0, rows);
        trpos.col = genrand(0, cols);
        trcount++;
    }
  
    /* Draw treasure */
    trpos = drawfigure(trpos, TREASURE, trpos, BACKGROUND, oldrows, oldcols);
    /* Remember screensize */
    oldrows = rows, oldcols = cols;
    if (plpos.row == trpos.row && plpos.col == trpos.col) { /* Player hit it */
        trcount--;
        mvaddch(trpos.row, trpos.col, PLAYER); /* Use player char to erase old
                                               treasure, to cover the situation
                                               where player stopped on top of
                                               treasure */
        return HIT;
    }
    return MISS;
}
Exemple #8
0
int main()  {
 
  int lattice[L] = {[0 ... L-1] = 0};
  int i, drop;
  int k;
  for(k = 0; k<L; k++) {printf("%i", lattice[k]); }
  printf(" --- End of initialisation\n");   

  sgenrand(time(NULL));

  for (drop = 0; drop < N_ROLLS; drop++) {  // big droppping cycle

  lattice[C] = lattice[C] + 1;  //actual drop in the drop location

  printf("\n");
  for(k = 0; k<L; k++) {printf("%i", lattice[k]); } // check after initial drop
  printf( " --- After %i drops************************************", drop+1);  

  for (i = 0; i < L; i++) {

    if (lattice[i] > 1) //check slots > 1
     {  
      // draw 2 rand nums
      int dist1 = genrand()*2; 
      int dist2 = genrand()*2;
      
       // convert to distr

       // define direction
      double  dir1 = genrand();
      double  dir2 = genrand();
      if(dir1 < 0.5) {dir1 = (int)-1;} else {dir1 = (int)1;}
      if(dir2 < 0.5) {dir2 = (int)-1;} else {dir2 = (int)1;}

      printf("\nBall 1 from cell %i moves: %i (%i,%i)", i, (int)dist1*(int)dir1, (int)dist1, (int)dir1);
      printf("\nBall 2 from cell %i moves: %i  (%i,%i)\n", i, (int)dist2*(int)dir2, (int)dist2,(int)dir2);

      // shoot 2 balls
      if(i+dist1*dir1 < L && i+dist1*dir1 >= 0) {lattice[i+(int)dist1*(int)dir1] = lattice[i+(int)dist1*(int)dir1] + 1;}
      if(i+dist2*dir2 < L && i+dist2*dir1 >= 0) {lattice[i+(int)dist2*(int)dir2] = lattice[i+(int)dist2*(int)dir2] + 1;}
      // decrease initial slot by 2
      lattice[i] = lattice[i] - 2;
      
      printf("Final standing after shooting:  ");
      for(k = 0; k<L; k++) {printf("%i", lattice[k]); } 

      // restart array check from beginning
      i = -1 ;  // account for autoincrement
      }  

    else {printf("\nNothing to shoot from cell %i", i); }  

    }
  } 
}
Exemple #9
0
double * user_unif_rand() {
#ifdef _OPENMP
  unsigned int tn;
  tn = omp_get_thread_num();
  res[tn] = genrand();
  return &res[tn];
#else
  *res = genrand();
  return res;
#endif
}
Exemple #10
0
point jitter_view()
{
	//The AA example in class used gluLookAt, which would require me to recalculate the eye, view, and up directions to maintain orientation.  I can get a similar
	//jittering effect just by translating the ModelView matrix, which doesnt reset it.  
	point viewJitter;
	viewJitter.x = -JITTER + 2.0*JITTER*genrand();
	viewJitter.y = -JITTER + 2.0*JITTER*genrand();
	viewJitter.z = -JITTER + 2.0*JITTER*genrand();
	glTranslatef(viewJitter.x, viewJitter.y, viewJitter.z);
	return viewJitter;
}
Exemple #11
0
static long mti_dist_uniform(long*seed, long start, long end)
{
      if (start >= end) return start;

      if ((start > LONG_MIN) || (end < LONG_MAX)) {
	    long range = end - start;
	    return start + genrand(&global_context)%range;
      } else {
	    return genrand(&global_context);
      }
}
Exemple #12
0
static long mti_dist_uniform(long*seed, long start, long end)
{
      (void)seed; /* Parameter is not used. */
      if (start >= end) return start;

      if ((start > LONG_MIN) || (end < LONG_MAX)) {
	    long range = end - start;
	    return start + genrand(&global_context)%range;
      } else {
	    return genrand(&global_context);
      }
}
void view_volume(float *ep, float *vp, int jitter) {
	vp[0] += JITTER*genrand();
	vp[1] += JITTER*genrand();
	vp[2] += JITTER*genrand();
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0,(float)(XRES)/(float)(YRES),0.1,20.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(ep[0],ep[1],ep[2],vp[0],vp[1],vp[2],0.0,1.0,0.0);
}
Exemple #14
0
int 
network_send_pkt(network_address_t dest_address, int hdr_len, 
                 char* hdr, int data_len, char* data) {

  if (synthetic_network) {
    if(genrand() < loss_rate)
      return (hdr_len+data_len);

    if(genrand() < duplication_rate)
      send_pkt(dest_address, hdr_len, hdr, data_len, data);
  }

  return send_pkt(dest_address, hdr_len, hdr, data_len, data);
}
void MainWindow::addNoise(){
    for(unsigned int i = 0; i < NT; i++){
        for(unsigned int j = 0; j < NT; j++){
            noisy[i][j] = (genrand() < noiseLevel ? -1.0 : 1.0) * image[i][j];
        }
    }
}
Exemple #16
0
int main(int argc, char**argv){
	unsigned int seed=19650218, count=100000,threadid=0,i;
        RandType ran0[RAND_BUF_LEN] __attribute__ ((aligned(16)));
        RandType ran1[RAND_BUF_LEN] __attribute__ ((aligned(16)));

	if(argc>=2)
		count=atoi(argv[1]);
        if(argc>=3) 
                seed=atoi(argv[2]);

	if(count==0 || seed==0 || argc==1){ /*when atoi returned error*/
		usage(argv[0]);
		exit(0);
	}

	if(seed<0) seed=time(NULL);

#pragma omp parallel private(ran0,ran1,threadid)
{
#ifdef _OPENMP
	threadid=omp_get_thread_num();	
#endif
	rng_init(ran0,ran1,(unsigned int *)&seed,threadid);

#pragma omp for
	for(i=0;i<count;i++){
		genrand(threadid,i,ran0,ran1);
	}
}
	return 0;
}
static int Lvalue(lua_State *L)			/** value(c,[a,b]) */
{
 MT *c=Pget(L,1);
 double a,b,r=genrand(c);
 switch (lua_gettop(L))
 {
  case 1:
   lua_pushnumber(L,r);
   return 1;
  case 2:
   a=1;
   b=luaL_checknumber(L,2);
   break;
  default:
   a=luaL_checknumber(L,2);
   b=luaL_checknumber(L,3);
   break;
 }
 if (a>b) { double t=a; a=b; b=t; }
 a=ceil(a);
 b=floor(b);
 if (a>b) return 0;
 r=a+floor(r*(b-a+1));
 lua_pushnumber(L,r);
 return 1;
}
/*
 * Return `true' p% of the time.
 */
bool
DefaultRndNumGenerator::rnd_flipcoin(const unsigned int p, const Filter *f, const std::string *)
{
	assert(p <= 100);
	unsigned INT64 local_depth = rand_depth_;
	rand_depth_++;
	if (f) {
		if (f->filter(0)) {
			add_number(1, 2, local_depth);
			return true;
		}
		else if (f->filter(1)) {
			add_number(0, 2, local_depth);
			return false;
		}
	}

	bool rv = (genrand() % 100) < p;
	if (rv) {
		add_number(1, 2, local_depth);
	}
	else {
		add_number(0, 2, local_depth);
	}
	return rv;
}
Exemple #19
0
/// throws random data into blockData
// returns 0 on success
// returns 1 when the block is a NULL pointer.
short block_random_fill(struct blockData *block, float range_low, float range_high){
	
	// check for block pointer being NULL.
	if(block == NULL){
		error("block_random_fill() could not fill block. block = NULL.");
		return 1;
	}
	
	// shiffle around the range values if they are not right.
	if(range_low > range_high){
		float temp = range_high;
		range_high = range_low;
		range_low = temp;
	}
	
	int j, i;
	
	// this will generate data that will statistically average zero.
	// the data will not average zero for each set of numbers however.
	for(i=0; i<BLOCK_WIDTH; i++){
		for(j=0; j<BLOCK_HEIGHT; j++){
			// generate a random number between range_low and range_high.
			block->elevation[i][j] = ((genrand()%100001)/100000.0)*(range_high-range_low) + range_low;//((rand()%100001)/100000.0)*(range_higher-range_lower)-((range_higher+range_lower)/2);
		}
	}
	
	// render the block next time it needs to be printed
	block->renderMe = 1;
	// generated random data in block successfully.
	return 0;
}
Exemple #20
0
double
rng_gauss(const double sigma)
{
	double x, y, r2;

	x=2.0*genrand()-1.0;
	/* get a y until (x,y) is inside unit circle */
	do {
		y=2.0*genrand()-1.0;
		r2=x*x+y*y;
	} while (r2>1.0);

	if (r2==0.0) return 0; /* very unlikely so we'll handle it trivially */

	return sigma*y*sqrt(-2.0*log(r2)/r2);
}
Exemple #21
0
int randompick(double prob[], int maxint)
{
	double x, sumprob = 0;
	int z = 0, choose = 0, i = -1;

	/* x determines the target variable */
	x = genrand();

	do
	{
		i++;
		sumprob += prob[i];
		if (x <= sumprob)
		{
			choose = i;
			z = 1;
		}
	} while (!z);

	if (choose > maxint){
		fprintf(stderr,"choose: %d maxint: %d\n",choose,maxint);
		for (i = 0; i<=choose; i++) fprintf(stderr,"%d %f\n",i,prob[i]);
		fprintf(stderr,"bad probability sum in randompick!\n");
		exit(1);
	}

	return choose;
}
int 
network_send_pkt(network_address_t dest_address, int hdr_len, 
		 char* hdr, int data_len, char* data) {
  //printf("network_send_pkt: called\n"); //DEBUG
  //printf("network_send_pkt : synthetic network - %d\n", synthetic_network);
  if (synthetic_network) {
    if(genrand() < loss_rate)
      return (hdr_len+data_len);

    if(genrand() < duplication_rate)
      send_pkt(dest_address, hdr_len, hdr, data_len, data);
  }

  //printf("call send_pkt\n");
  return send_pkt(dest_address, hdr_len, hdr, data_len, data);
}
Exemple #23
0
void jitter_view()
{
struct point eye, view, up, vdir, utemp, vtemp;

eye.x = 2.0; eye.y = 2.0; eye.z = 2.0;
view.x = JITTER*genrand(); view.y = JITTER*genrand(); view.z = JITTER*genrand();
up.x = 0.0; up.y = 1.0; up.z = 0.0;
vdir.x = view.x - eye.x; vdir.y = view.y - eye.y; vdir.z = view.z - eye.z;
// Calculate correct up vector as orthogonal to vdir and in the plane of
// vdir and (0,1,0).
vtemp = cross(vdir,up);
utemp = cross(vtemp,vdir);
up = unit_length(utemp);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(eye.x,eye.y,eye.z,view.x,view.y,view.z,up.x,up.y,up.z);
}
int JPAKE_STEP1_generate(JPAKE_STEP1 *send, JPAKE_CTX *ctx)
    {
    genrand(ctx);
    generate_step_part(&send->p1, ctx->xa, ctx->p.g, ctx);
    generate_step_part(&send->p2, ctx->xb, ctx->p.g, ctx);

    return 1;
    }
int YAK_STEP1_generate(YAK_STEP1 *send, YAK_CTX *ctx)
    {
    genrand(ctx);
    generate_step_part(&send->p1, ctx->xa, ctx->p.g, ctx);
    generate_step_part(&send->p2, ctx->xb, ctx->p.g, ctx);

    return 1;
    }
static int sys_random_calltf(char*name)
{
      s_vpi_value val;
      vpiHandle call_handle;
      vpiHandle argv;
      vpiHandle seed = 0;
      int i_seed = 0;
      struct context_s *context;

      call_handle = vpi_handle(vpiSysTfCall, 0);
      assert(call_handle);

	/* Get the argument list and look for a seed. If it is there,
	   get the value and reseed the random number generator. */
      argv = vpi_iterate(vpiArgument, call_handle);
      if (argv) {
	    seed = vpi_scan(argv);
	    vpi_free_object(argv);

	    val.format = vpiIntVal;
	    vpi_get_value(seed, &val);
	    i_seed = val.value.integer;

	      /* Since there is a seed use the current 
	         context or create a new one */
	    context = (struct context_s *)vpi_get_userdata(call_handle);
	    if (!context) {
		  context = (struct context_s *)calloc(1, sizeof(*context));
		  context->mti = NP1;
		  assert(context);

		    /* squrrel away context */
		  vpi_put_userdata(call_handle, (void *)context);
	    }

	      /* If the argument is not the Icarus cookie, then
		 reseed context */
	    if (i_seed != COOKIE)
	          sgenrand(context, i_seed);
      } else {
	    /* use global context */
          context = &global_context;
      }

      val.format = vpiIntVal;
      val.value.integer = genrand(context);

      vpi_put_value(call_handle, &val, 0, vpiNoDelay);

        /* mark seed with cookie */
      if (seed && i_seed != COOKIE) {
	    val.format = vpiIntVal;
	    val.value.integer = COOKIE;		
	    vpi_put_value(seed, &val, 0, vpiNoDelay);
      }

      return 0;
}
Exemple #27
0
/*
   Fills file with given data
   Returns SCRUB_ERR in case of error, otherwise returns SCRUB_OK
*/
int Scrubber::FillFile(int fdFile, off64_t nFileSize, char* arrData, unsigned int nSize, bool bRandomize)
{
    //       Add progress update
    off64_t nWritten = 0LL;

    int nBytes = 0;

    lseek(fdFile, 0, SEEK_SET);

    if (bRandomize)
    {
        if (churnrand() != 0)
        {
            snprintf(sLogBuf, MESSAGE_LEN, "ERROR: Occured in churnrand(). Inside function FillFile().\n");
            WriteToLog(ScrubLogger::SCRUB_ERROR, this->nCurrFile, sLogBuf);

            return SCRUB_ERR;
        }
    }

    while (nWritten < nFileSize)
    {
        // Randomise buffer if needed
        if (bRandomize)
        {
            genrand(arrData, nSize);
            //Random::GetInstance()->FillRand(arrData, nSize, 0, 255);
        }

        // Make sure we won't write out of file bounds
        if (nWritten + nSize > nFileSize)
        {
            nSize = nFileSize - nWritten;
        }

        // Write Data
        nBytes = WriteData(fdFile, arrData, nSize);

        if (nBytes < 0)
        {
            snprintf(sLogBuf, MESSAGE_LEN, "ERROR: %s. Occured while writing data to file %s. Inside function FillFile().\n",
                    strerror(errno), this->lstFiles->at(this->nCurrFile).c_str());
            WriteToLog(ScrubLogger::SCRUB_ERROR, this->nCurrFile, sLogBuf);

            this->nTotalWritten += nFileSize - nWritten;

            return SCRUB_ERR;
        }

        nWritten += nBytes;
        this->nTotalWritten += nBytes;

        // Report progress
        UpdateProgress();
    }

    return SCRUB_OK;
}
Exemple #28
0
int
network_bcast_pkt(int hdr_len, char* hdr, int data_len, char* data)
{
    int i;
    int me;

    AbortOnCondition(!BCAST_ENABLED,
                     "Error: network broadcast not enabled.");

    if (BCAST_USE_TOPOLOGY_FILE) {

        me = topology.me;

        for (i=0; i<topology.entries[me].n_links; i++) {
            int dest = topology.entries[me].links[i];

            if (synthetic_network) {
                if(genrand() < loss_rate)
                    continue;

                if(genrand() < duplication_rate)
                    send_pkt(topology.entries[dest].addr, hdr_len, hdr, data_len, data);
            }

            if (send_pkt(topology.entries[dest].addr,
                         hdr_len, hdr, data_len, data) != hdr_len + data_len)
                return -1;
        }

        if (BCAST_LOOPBACK) {
            if (send_pkt(topology.entries[me].addr,
                         hdr_len, hdr, data_len, data) != hdr_len + data_len)
                return -1;
        }

    } else { /* real broadcast */

        /* send the packet using the private network broadcast address */
        if (send_pkt(broadcast_addr,
                     hdr_len, hdr, data_len, data) != hdr_len + data_len)
            return -1;

    }
    return hdr_len+data_len;
}
Exemple #29
0
/** @brief The workhorse thread of the test.
 *
 *  This thread recursively spawns two copies of itself decrementing n_voidstar
 *  so long as n_voidstar is positive. Each thread repeats this process n_throws
 *  times, after joining on the threads it created.
 *
 *  @param The level we are at (to keep us from infinitly recursively spawning.
 */
void *juggle(void * n_voidstar)
{
    int sub1, sub2;
    int throws;
    int substat;
    int ret;
    int n = (int)n_voidstar;

    inc_count();
    print_count(n);

    if (n > 0) {
        for (throws = 0; throws < n_throws; throws++) {
    
            // Toss up two balls
            sub1 = thr_create(juggle, (void *)(n - 1));
        
            if (sub1 < 0) {
                lprintf("Lev %d failed to create first thread w/ err %d\n",
                        n, sub1);
            }
    
            sub2 = thr_create(juggle, (void *)(n - 1));
    
            if (sub2 < 0) {
                lprintf("Lev %d failed to create second thread w/ err %d\n",
                        n, sub2);
            }
    
            // Try to catch them
            if ((ret = thr_join(sub1, (void*)&substat))
                 != 0 || substat != (n - 1)) {
              lprintf("Lev %d failed to join first thread correctly:\n\t", n);
              lprintf("join(%d), ret = %d, %d ?= %d\n",
                                    sub1, ret, (n - 1), substat);
            }
            
            if ((ret = thr_join(sub2, (void*)&substat))
                != 0 || substat != (n - 1)) {
              lprintf("Lev %d failed to join second thread correctly:\n\t", n);
              lprintf("join(%d), ret = %d, %d ?= %d\n",
                                    sub2, ret, (n - 1), substat);
            }
        }
    }
#ifdef PRINT
    // Tell that we were successfull.
    putchar((char)n + '0');
#endif

    print_count(n);

    // Hang in the air for some amount of time
    sleep(genrand() % SLEEP_MAX);
    
    return (void *)n;
}
Exemple #30
0
double rand0to1(){
	double x;
#ifdef USING_MT
	x = genrand();
#else
	x = (double) rand() / (double) RAND_MAX;
#endif
	return x;
}