Ejemplo n.º 1
0
double RandMaster::randg( double mu, double sigma )
{
    /// @tod:  Document this function / algorithm

    double v1  = 0.0,
           v2  = 0.0,
           rsq = 0.0,
           fac = 0.0;

    if( lastGauss == DBL_MAX )
    {
        while( rsq >= 1.0 || rsq == 0.0 )
        {
            v1 = randd( -1.0, 1.0 );
            v2 = randd( -1.0, 1.0 );
            rsq = v1*v1 + v2*v2;
        }
        fac = sqrt( -2.0 * log( rsq ) / rsq );
        lastGauss = v1 * fac;
        fac *= v2;
    }

    else
    {
        fac = lastGauss;
        lastGauss = DBL_MAX;
    }
    return mu + sigma * fac;
}
Ejemplo n.º 2
0
double randn(){
    // box-muller transform
    double u1     = randd();
    double u2     = randd();
    double R      = sqrt(-2*log(u1));
    double theta  = 6.283185307179586*u2;
    return R*cos(theta);
}
Ejemplo n.º 3
0
/**********************************************************************
 * 迭代
 **********************************************************************/
void tran()
{
    int i, j, pos;
    int k;
    //找当前种群最优个体 
    min = cur[0];
    for ( i=1; i<SIZE-1; i++ ) {
        if ( cur[i].fitness<min.fitness ) {
            min = cur[i];
        }
    }
    for ( k=0; k<SIZE; k+=2 ) {
        // 选择交叉个体 
        i = sel();
        j = sel();
        
        // 选择交叉位置 
        pos = randi(LEN-1);
        
        //交叉
        if ( randd()<P_CORSS ) {
            memcpy(next[k].x, cur[i].x, pos);
            memcpy(next[k].x+pos, cur[j].x+pos, LEN-pos);
            memcpy(next[k+1].x,cur[j].x,pos);
            memcpy(next[k+1].x+pos,cur[i].x+pos,LEN-pos);
        } else {
            memcpy(next[k].x,cur[i].x,LEN);
            memcpy(next[k+1].x,cur[j].x,LEN);
        }
        //变异
        if ( randd()<P_MUTATION ) {
            pos = randi(LEN-1);
            next[k].x[pos] ^= next[k].x[pos];
         
            pos = randi(LEN-1);
            next[k+1].x[pos] ^= next[k+1].x[pos];
        }
    }
    //找下一代的最差个体 
    max = next[0];
    j = 0;
    
    for ( i=1; i<SIZE-1; i++ ) {
        if ( next[i].fitness<min.fitness ) {
            max = next[i];
            j = i;
        }
    }
    //用上一代的最优个体替换下一代的最差个体
    next[j] = min;
    
    memcpy(cur, next, sizeof(cur));
    
    cal_fitness();
}
Ejemplo n.º 4
0
void World::init (int sizeX, int sizeY, int sizeV, int tDur, double lRate) {
	int x, y, i, j, nCount = 0;
	double state;
	
	this->clear();

	_sizeX = sizeX; _sizeY = sizeY; _vectorSize = sizeV;
	_trainDur = tDur; _learningRate = lRate; _initLearningRate = lRate;

	_mapRadius = (double)max(_sizeX, _sizeY) / 2.0f;
	
	_timeConst = (double)(_trainDur / logf(_mapRadius));
	
	for (int i = 0; i < 8; i++) 
		neighborWeights.push_back(1.0);
		
	nodes = new Node*[_sizeX];
	assert(nodes);
	for (x = 0; x < _sizeX; x++) {
		nodes[x] = new Node[_sizeY];
		assert(nodes[x]);
		for (y = 0; y < _sizeY; y++) {
			nodes[x][y].x = x;
			nodes[x][y].y = y;
			for (i = 0; i < _vectorSize; i++) {
				state = randd();
 				nodes[x][y].weights.push_back(state);
			}
			state = randd();
			for (i = 0; i < 3; i++) {
				nodes[x][y].states[i] = 0;			
			}
			
		}
	}
	
	for (x = 0; x < _sizeX; x++) {
		for (y = 0; y < _sizeY; y++) {
			nCount = 0;
			for (i = 0; i < 3; i++) {
				for (j = 0; j < 3; j++) {
					if (!(i == 1 && j == 1)) {
//						nodes[x][y].neighbors[nCount] = &(nodes[wrapi(x+(i-1), 0, _sizeX-1)][wrapi(y+(j-1), 0, _sizeY-1)]);
						nodes[x][y].neighbors[nCount] = &(nodes[fold(x+(i-1), 0, _sizeX-1)][fold(y+(j-1), 0, _sizeY-1)]);
						nCount++;
					}
				}
			}
			
		}
	}
	
}
Ejemplo n.º 5
0
static void rand_gaussd( double& y1, double& y2 ) {
    double x1, x2, w;
    do {
        x1 = 2.0 * randd() - 1.0;
        x2 = 2.0 * randd() - 1.0;
        w = x1 * x1 + x2 * x2;
    } while ( w >= 1.0 );

    w = sqrt( (-2.0 * log( w ) ) / w );
    y1 = x1 * w;
    y2 = x2 * w;
}
Ejemplo n.º 6
0
static void swarmer_burst_fn(struct ecs_entity *pod) {
  ecs_entity *target;
  while ((target = list_popfront(lockon_list))) {
    fire_at_target(pod, target, randd(0, 2 * PI));
  }
  explode(pod);
}
Ejemplo n.º 7
0
inline void trajectory(double* act) {
    /*trajectory tau, t, d, p*/
    int k, j = 1;
    p_str[1].t = p_str[1].p = 0.;
    while ( p_str[j].t <= Tmax ) {
        p_str[j].tau = log( 1/(RAND() + 0.0000001 ) ) / kappa;
        p_str[j].d = randd();
        j++;
        p_str[j].t = p_str[j-1].t + p_str[j-1].tau;
        p_str[j].p = p_str[j-1].p + p_str[j-1].d;
    }


    if (j>1) p_str[j-1].tau = Tmax - p_str[j-1].t;
    else p_str[j].t = Tmax;
    /*end trajectory*/
    j--;

    if (j == 1) act[1] = act[2] = act[3] = act[4] = 0.;
    else {
        act[1] = j-1;
        act[2] = p_str[j].p;
        act[3] = act[4] = 0.;
        for (k=1; k<=j-1; k++)  {
            act[3] += p_str[k].tau * (p_str[k].p + E0*(p_str[k+1].t-p_str[k].tau/2.));
            act[4] += Phi(p_str[k].d) +
                      ( M_PI + p_str[k].tau*( p_str[k].p + E0*( p_str[k].t-p_str[k].tau/2. )*( p_str[k].t-p_str[k].tau/2. )
                                              + E0*E0 * p_str[k].tau * p_str[k].tau * p_str[k].tau / 12. )
                      ) / 2.;
        }
    }
}
Ejemplo n.º 8
0
Archivo: Gene.cpp Proyecto: bog2k3/bugs
Gene Gene::createRandomSkipGene(int spaceLeftAfter) {
	GeneSkip g;
	g.minDepth.set(randi(10));
	g.maxDepth.set(g.minDepth + randi(10-g.minDepth));
	// use a random distribution that favors small values:
	g.count.set(sqr(randd()) * spaceLeftAfter);
	return g;
}
Ejemplo n.º 9
0
void
GameState::resetBall() {
  m_ball.position = Point2d(.5, .5);

  double r = getVelocityMagnitude();
  double a = (0.75 - randd() / 2) * PI;
  m_ball.velocity = Vector2d(r * cos(a), r * -sin(a));
}
Ejemplo n.º 10
0
void
GameState::buildLevel() {
  m_blocks.clear();
  for (int x = 0; x < 10; ++x) {
    for (int y = 0; y < 5; ++y) {
      Block bl;
      int x1 = x + 1;
      int y1 = y + 1;
      bl.location = Rectangle(
	x  / 10.0, y  / 50.0 + .05,
	x1 / 10.0, y1 / 50.0 + .05);
      double r = (randd() + 1) / 2;
      double g = (randd() + 1) / 2;
      double b = (randd() + 1) / 2;
      bl.color = Color3d(r, g, b);
      m_blocks.push_back(bl);
    }
  }
}
Ejemplo n.º 11
0
void init()
{
    Node node;
    for(int i=0;i<N;i++)
    {
        node = getNodepointer(ori_graph,1);
        price_discount[i]=ori_price[0];//初始折扣赋给price_discount
        //printf("price_discount[%d] is %f\t",i,price_discount[i]);
        price_v[i]=randd()*Vmax;

        for(int j=0;j<dim;j++)
        {
            x[i][j]=(double)node->infln; //初始影响状态赋给x
            //printf("x[%d][%d] is %f\n",i,j,x[i][j]);
            v[i][j]=randd()*Vmax;
            node = node->next;
        }
    }
    
    //把*price_discount和**x合并为**p
    {for(int m=0;m<N;m++)
        p[m][0]=price_discount[m];
        for(int f=0;f<N;f++)
            for(int k=0;k<dim;k++)
                p[f][k+1]=x[f][k];
    }
    
    //把*price_v和**v合并为**v_all
    {for(int m=0;m<N;m++)
        v_all[m][0]=price_v[m];
        for(int f=0;f<N;f++)
            for(int k=0;k<dim;k++)
                v_all[f][k+1]=v[f][k];
    }
    node = getNodepointer(ori_graph, 1);
    for(int i=0;i<N;i++)
    {
        y[i] = influenceAll(node, 1, ori_price[0]);
        pbest[i] = y[i]; //初始化局部最优
    }
    gbest = pbest[0]; //初始化全局最优
}
Ejemplo n.º 12
0
int sel()
{
    double p = randd();
    double sum = cur[SIZE-1].fitsum;
    int i;
    
    for ( i=0; i<SIZE; i++ ) {
        if( cur[i].fitsum/sum>p ) {
            return i;
        } 
    }
}
Ejemplo n.º 13
0
// helper to set up particle attributes
static particle* make_particle(generator_data *data, vector pos, double angle) {
  double angle1 = angle - data->spawn_arc / 2;
  double angle2 = angle + data->spawn_arc / 2;
  particle *p = malloc(sizeof(particle));
  p->position = pos;
  p->velocity = rand_vec(angle1, angle2, data->spawn_velocity, data->max_velocity);
  p->time_alive = 0;
  p->time_to_live = randd(data->min_duration, data->max_duration);
  p->radius = data->start_radius;
  p->color = data->start_color;
  p->data = data;
  return p;
}
Ejemplo n.º 14
0
/**
 * Return a random integer i where 0 <= i < n.
 */
static int32_t randi(int32_t n)
{
    return (int32_t)(randd() * n);
}
Ejemplo n.º 15
0
/*
 * eq: equlibirium factor
 * ti: temperature initial
 * te: temperature end
 * cf: cooling factor (0 < cf < 1)
 */
uint32_t simulated_annealing(sat_t *sat, double te, double steps) {
	state_t *state = state_init(sat->vars_cnt, STATE_RANDOMIZE);
	state_t *state_next = state_init(sat->vars_cnt, STATE_ALL_0);
	uint32_t ret = 0;
	uint32_t real_cost = 0;
	uint32_t eq; /* equlibrium */
	double cf; /* cooling factor */
	double ti; /* temperature initial */

	ti = sat->vars_cnt * sat->weight_max * 10;
	cf = pow(te / ti, 1 / (steps - 1));
//	cf = 1 - ((ti - te) / steps);

	static bool print_once = false; //true;

	uint32_t it = 0;

//	printf("ti=%lf te=%lf cf=%lf, eq=%d\n", ti, te, cf, eq);

//	for (double t = ti; te < t; t *= cf) {
//		for (int i = 0; i < eq; i++) {
//			state_gen_next(state, state_next);
//			double d = ((double) cost(sat, state))
//					- ((double) cost(sat, state_next));
//
//			if (d < 0 || randd() < pow(M_E, -d / t)) {
//				state_swap(&state, &state_next);
//				continue;
//			}
//
//			//printf("it= %4u best= %4u bits= ", it++, cost(sat, state));
//			//			state_print(state);
//		}
//	}
	//http://www.cs.ubc.ca/~hoos/SATLIB/benchm.html
	eq = (uint32_t) (sat->vars_cnt / (double) 2.0);
	uint32_t *p = calloc(sat->vars_cnt, sizeof(uint32_t));
	for (double t = ti; te < t; t *= cf) {
		permutation(p, sat->vars_cnt);
		it++;
//		printf("t=%lf\n", t);
		for (uint32_t i = 0; i < eq; i++) {

			double c = cost(sat, state);

			uint32_t ind = p[i];
			state->ch[ind] = (state->ch[ind] + 1) % 2;

			double d = (c - (double) cost(sat, state));

			if (d < 0 || randd() < pow(M_E, -d / t)) {
				continue;
			}

			state->ch[ind] = (state->ch[ind] + 1) % 2;
		}

		real_cost = cost_main(sat, state);

		if (g_print_progress) {
			printf("%u %u %lf\n", it, real_cost, cost(sat, state));
		}

		ret = max(ret, real_cost);
	}

	if (print_once) {
		fprintf(stderr, "ti=%lf cf=%lf it=%u eq=%u\n", ti, cf, it, eq);
		assert(0 < cf && cf < 1);
		print_once = false;
		state_print(state);
	}

	free(p);
	state_free(state);
	state_free(state_next);

	return (ret);
}
Ejemplo n.º 16
0
void pso()
{
    int i,g,tag=1,count1=0,rest1=0;
    double w;
    double max_x=0;
    Node node,retnode;
    for(g=0;g<G;g++)//进行G轮迭代
    {
        w=w2+(w1-w2)*(G-g)/G;
        for(i=0;i<N;i++)
        {
            for(int j=0;j<dim+1;j++)
            {
                v_all[i][j]=w*v_all[i][j]+c1*randd()*(pbest[i]-p[i][j])+c2*randd()*(gbest-p[i][j]);
                if(v_all[i][j]>Vmax)
                    v_all[i][j]=Vmax;
                if(v_all[i][j]<Vmin)
                    v_all[i][j]=Vmin; //速度约束
                
                p[i][j]+=v_all[i][j];
                if(p[i][j]<=0)
                    p[i][j]=0;
                if(p[i][j]>=1)
                    p[i][j]=1; //粒子群约束
                //printf("update round %d , p[%d][%d] is %f\n",g,i,j,p[i][j]);
            }
            for(int j=1;j<dim+1;j++)
            {
                if(p[i][j] == 1)
                    count1++;
                rest1 = NumOri_Nodes - count1; //还需选出几个1
            }
            
            for(int k=0;k<rest1;k++)
            {
                for(int j=1;j<dim+1;j++)
                {
                    if(p[i][j]>0 && p[i][j]<1)
                    {
                        max_x = p[i][j];
                        tag = j;
                        break;
                    }
                }
                for(int j=1;j<dim+1;j++)
                {
                    if(p[i][j]>0 && p[i][j]<1)
                    {
                        max_x = MAX(max_x, p[i][j]);
                        if(max_x == p[i][j])
                            tag = j;
                    }
                }
                p[i][tag] = 1; //选出最接近1的值,另其为1
            }
            
            for(int j=1;j<dim+1;j++)
            {
                if(p[i][j] != 1)
                    p[i][j] = 0;
            } //对于不是1的值,均另其为0
            
        }//更新一次v_all和p
        
        node = copy_graph_nodes(ori_graph);
        retnode = node;
        
        for(int i=0;i<N;i++)
        {
            ori_price[i] = p[i][0];
            for(int j=1;j<dim+1;j++)
            {
                node->infln = p[i][j];
                node = node->next;
            }
            node = retnode;
            y[i] = influenceAll(node, 1,ori_price[i]);
        }
        
        for(i=0;i<N;i++)
        {
            pbest[i]=MAX(pbest[i],y[i]);
            gbest=MAX(gbest,pbest[i]);
        }
        //printf("update round %d of gbest is %f\n",g+1,gbest);
        //printf("\n");
    }
    printf("\n");
    printf("final result:gbest is %f\n",gbest);
}
Ejemplo n.º 17
0
float RandMaster::randf( float lo, float hi )
{
    return (float)randd( lo, hi );
}
Ejemplo n.º 18
0
Archivo: Gene.cpp Proyecto: bog2k3/bugs
Gene Gene::createRandom(int spaceLeftAfter, int nNeurons) {
	std::vector<std::pair<gene_type, double>> geneChances {
		// these are relative chances:
		{gene_type::BODY_ATTRIBUTE, 1.0},
		{gene_type::PROTEIN, 1.5},
		{gene_type::PART_ATTRIBUTE, 2.1},
		{gene_type::OFFSET, 0.3},
		{gene_type::JOINT_OFFSET, 0.3},
		{gene_type::NEURAL_BIAS, 1.0},
		{gene_type::NEURAL_PARAM, 0.8},
		{gene_type::TRANSFER_FUNC, 0.5},
		{gene_type::SYNAPSE, 1.5},
		{gene_type::NEURON_INPUT_COORD, 0.5},
		{gene_type::NEURON_OUTPUT_COORD, 0.5},
		{gene_type::SKIP, 0.12},
#ifdef ENABLE_START_MARKER_GENES
		{gene_type::START_MARKER, 0.1},
#endif
		{gene_type::STOP, 0.09},
		{gene_type::NO_OP, 0.09},
	};
	// normalize chances to make them sum up to 1.0
	double total = 0;
	for (auto &x : geneChances)
		total += x.second;
	for (auto &x : geneChances)
		x.second /= total;
	double dice = randd();
	double floor = 0;
	gene_type type = gene_type::INVALID;
	for (auto &x : geneChances) {
		if (dice - floor < x.second) {
			type = x.first;
			break;
		}
		floor += x.second;
	}
	switch (type) {
	case gene_type::BODY_ATTRIBUTE:
		return createRandomBodyAttribGene();
	case gene_type::PROTEIN:
		return createRandomProteinGene();
	case gene_type::OFFSET:
		return createRandomOffsetGene(spaceLeftAfter);
	case gene_type::JOINT_OFFSET:
		return createRandomJointOffsetGene(spaceLeftAfter);
	case gene_type::NEURON_INPUT_COORD:
		return createRandomNeuronInputCoordGene(nNeurons);
	case gene_type::NEURON_OUTPUT_COORD:
		return createRandomNeuronOutputCoordGene(nNeurons);
	case gene_type::NEURAL_BIAS:
		return createRandomNeuralBiasGene(nNeurons);
	case gene_type::PART_ATTRIBUTE:
		return createRandomAttribGene();
	case gene_type::SKIP:
		return createRandomSkipGene(spaceLeftAfter);
#ifdef ENABLE_START_MARKER_GENES
	case gene_type::START_MARKER:
		return GeneStartMarker();
#endif
	case gene_type::STOP:
		return GeneStop();
	case gene_type::SYNAPSE:
		return createRandomSynapseGene(nNeurons);
	case gene_type::TRANSFER_FUNC:
		return createRandomTransferFuncGene(nNeurons);
	case gene_type::NO_OP:
		return GeneNoOp();
	default:
		ERROR("unhandled gene random type: " << (uint)type);
		return GeneStop();
	}
}