int main()
{
	try
	{
		std::cout << Divide(5, 2) << std::endl;
		std::cout << Divide(10, 0) << std::endl;
		std::cout << Divide(3, 3) << std::endl;
	}
	catch (const std::invalid_argument& e)
	{
		std::cout << "Caught exception: " << e.what() << std::endl;
	}

	return 0;
}
Beispiel #2
0
void VirtualSpace_Release(uint32_t* logAddrToRealease, uint32_t nbPages)
{
	FreeSpace* nextFS = VirtualSpace_GetNextFreeSpace(logAddrToRealease);
	FreeSpace* prevFS = VirtualSpace_GetPrevious(nextFS);
	uint8_t createNewFS = 1;
	if((*nextFS).addrSpace==logAddrToRealease+nbPages*PAGE_SIZE)
	{
		(*nextFS).addrSpace = logAddrToRealease;
		(*nextFS).nbPagesFree += nbPages;

		createNewFS = 0;
	}
	
	if((*prevFS).addrSpace+(*prevFS).nbPagesFree*PAGE_SIZE==logAddrToRealease)
	{
		(*prevFS).nbPagesFree += nbPages;

		createNewFS = 0;
	}

	if(createNewFS)
	{		
		uint32_t nbMiniFrames;
		uint32_t mod;
		Divide(	sizeof(FreeSpace),
				MINI_FRAMES_SIZE_OF_A_FRAME+1,
				&nbMiniFrames,&mod);
		FreeSpace* newFS = (FreeSpace*)Mini_Alloc(nbMiniFrames,0);
		(*newFS).nbPagesFree = nbPages;
		(*newFS).addrSpace = logAddrToRealease;
		(*newFS).ptNextFreeSpace = nextFS;
		(*prevFS).ptNextFreeSpace = newFS;
	}

}
// Creates a sphere
Mesh* CreateSphere(int subdivisions)
{
    nextIndex = 0;
	// TODO: calc how many items in the arrays we need
    vertices = new Vertex[100000];
	vertexCurrentIndex = 0;
	indices = new USHORT[100000];
	indexCurrentIndex = 0;

    AddBaseTriangle(CreateVector(0, 0, 1), CreateVector(1, 0, 0), CreateVector(0, 1, 0));
    AddBaseTriangle(CreateVector(1, 0, 0), CreateVector(0, 0, -1), CreateVector(0, 1, 0));
    AddBaseTriangle(CreateVector(0, 0, -1), CreateVector(-1, 0, 0), CreateVector(0, 1, 0));
    AddBaseTriangle(CreateVector(-1, 0, 0), CreateVector(0, 0, 1), CreateVector(0, 1, 0));
    AddBaseTriangle(CreateVector(1, 0, 0), CreateVector(0, 0, 1), CreateVector(0, -1, 0));
    AddBaseTriangle(CreateVector(0, 0, -1), CreateVector(1, 0, 0), CreateVector(0, -1, 0));
    AddBaseTriangle(CreateVector(-1, 0, 0), CreateVector(0, 0, -1), CreateVector(0, -1, 0));
    AddBaseTriangle(CreateVector(0, 0, 1), CreateVector(-1, 0, 0), CreateVector(0, -1, 0));

    for (int division = 1; division < subdivisions; division++) Divide();

	Mesh* mesh = new Mesh();
	mesh->Set(vertices, vertexCurrentIndex, indices, indexCurrentIndex);

	// Free allocated arrays
	delete [] vertices;
	delete [] indices;

	return mesh;
}
int main()
{
	int x;
	int start=0,end=100;
	int y=(start+end)/2;
	printf("*****************************************************************\n");
	printf("Enter the number corresponding to the desired pay rate or action:\n");
	printf("a) add\t\t\ts) subtract\n");
	printf("m) multiply\t\td) divide\n");
	printf("q) quit\n");
	printf("*****************************************************************\n");
	x=getchar();
	switch(x)
	{
		case 'a':
			Add();
			break;
		case 's':
			Subtract();
			break;
		case 'm':
			Mutliply();
			break;
		case 'd':
			Divide();
			break;
		case 'q':
			printf("Bye~~~~~~\n");
			break;
	}
}
void efficiencyBinomialErrors()
{
  printf("\n Get the binomial errors for efficiencies\n\n");

  auto h_num = new TH1D("h_num", "h_num", nbins, 0, nbins);
  auto h_den = new TH1D("h_den", "h_den", nbins, 0, nbins);

  for (int i=0; i<nbins; i++)
    {
      h_num->SetBinContent(i+1, n_num[i]);
      h_den->SetBinContent(i+1, n_den[i]);
    }

  auto graph = new TGraphAsymmErrors();

  graph->Divide(h_num, h_den, "cl=0.683 b(1,1) mode");

  auto canvas = new TCanvas("canvas", "canvas");

  graph->SetMarkerStyle(kFullCircle);

  graph->Draw("apz");

  graph->Print();
}
Beispiel #6
0
void M2MFstAligner::expectation( ){
  /*
    Here we compute the arc posteriors.  This routine is almost 
    fun to implement in the FST paradigm.
  */
  for( unsigned int i=0; i<fsas.size(); i++ ){
    //Compute Forward and Backward probabilities
    ShortestDistance( fsas.at(i), &alpha );
    ShortestDistance( fsas.at(i), &beta, true );

    //Compute the normalized Gamma probabilities and 
    // update our running tally
    for( StateIterator<VectorFst<LogArc> > siter(fsas.at(i)); !siter.Done(); siter.Next() ){
      LogArc::StateId q = siter.Value();
      for( ArcIterator<VectorFst<LogArc> > aiter(fsas.at(i),q); !aiter.Done(); aiter.Next() ){
	const LogArc&      arc = aiter.Value();
	const LogWeight& gamma = Divide(Times(Times(alpha[q], arc.weight), beta[arc.nextstate]), beta[0]); 
	//Check for any BadValue results, otherwise add to the tally.
        //We call this 'prev_alignment_model' which may seem misleading, but
        // this conventions leads to 'alignment_model' being the final version.
	if( gamma.Value()==gamma.Value() ){
	  prev_alignment_model[arc.ilabel] = Plus(prev_alignment_model[arc.ilabel], gamma);
	  total = Plus(total, gamma);
	}
      }
    }
    alpha.clear();
    beta.clear();
  }
}
Beispiel #7
0
float
M2MFstAligner::maximization(bool lastiter)
{
    //Maximization. Simple count normalization.  Probably get an improvement
    // by using a more sophisticated regularization approach.
    map<LogArc::Label,LogWeight>::iterator it;
    float change = abs(total.Value() - prevTotal.Value());
    //cout << "Total: " << total << " Change: " << abs(total.Value()-prevTotal.Value()) << endl;
    prevTotal = total;

    //Normalize and iterate to the next model.  We apply it dynamically
    // during the expectation step.
    for (it = prev_alignment_model.begin();
            it != prev_alignment_model.end(); it++) {
        alignment_model[(*it).first] = Divide((*it).second, total);
        (*it).second = LogWeight::Zero();
    }

    for (int i = 0; i < fsas.size(); i++) {
        for (StateIterator<VectorFst<LogArc> > siter(fsas[i]);
                !siter.Done(); siter.Next()) {
            LogArc::StateId q = siter.Value();
            for (MutableArcIterator<VectorFst<LogArc> > aiter(&fsas[i], q); !aiter.Done(); aiter.Next()) {
                LogArc arc = aiter.Value();
                arc.weight = alignment_model[arc.ilabel];
                aiter.SetValue(arc);
            }
        }
    }

    total = LogWeight::Zero();
    return change;
}
Beispiel #8
0
/// <summary>
/// Overloaded operator (/) for solving the following equation: result = value1 / value2
/// </summary>
/// <param name="src">Large Integer value wich represet value2</param>
/// <returns>Result of operation</returns>
CLargeInteger CLargeInteger::operator / (const CLargeInteger &src)
{
    CLargeInteger res;

    Divide( this, &src, &res);

    return res;
}
Beispiel #9
0
void solve() {
	scanf("%d", &n);
	for (int i = 0; i < n; i++) scanf("%lf%lf", &p[i].x, &p[i].y), p[i].index = i, p[i].in = NULL;
	Alloc_memory(); sort(p, p + n);
	for (int i = 0; i < n; i++) Q[i] = p + i;
	edge *L, *R; Divide(0, n - 1, &L, &R);
	M = 0; Make_Graph(); Kruskal();
}
Beispiel #10
0
// Solution taken from: http://mathworld.wolfram.com/QuarticEquation.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a4,double a3,double a2,double a1,double a0,double roots[4][2],const double& EPS){
	double R[2],D[2],E[2],R2[2];

	if(fabs(a4)<EPS){return Factor(a3,a2,a1,a0,roots,EPS);}
	a3/=a4;
	a2/=a4;
	a1/=a4;
	a0/=a4;

	Factor(1.0,-a2,a3*a1-4.0*a0,-a3*a3*a0+4.0*a2*a0-a1*a1,roots,EPS);

	R2[0]=a3*a3/4.0-a2+roots[0][0];
	R2[1]=0;
	Sqrt(R2,R);
	if(fabs(R[0])>10e-8){
		double temp1[2],temp2[2];
		double p1[2],p2[2];

		p1[0]=a3*a3*0.75-2.0*a2-R2[0];
		p1[1]=0;

		temp2[0]=((4.0*a3*a2-8.0*a1-a3*a3*a3)/4.0);
		temp2[1]=0;
		Divide(temp2,R,p2);

		Add     (p1,p2,temp1);
		Subtract(p1,p2,temp2);

		Sqrt(temp1,D);
		Sqrt(temp2,E);
	}
	else{
		R[0]=R[1]=0;
		double temp1[2],temp2[2];
		temp1[0]=roots[0][0]*roots[0][0]-4.0*a0;
		temp1[1]=0;
		Sqrt(temp1,temp2);
		temp1[0]=a3*a3*0.75-2.0*a2+2.0*temp2[0];
		temp1[1]=                  2.0*temp2[1];
		Sqrt(temp1,D);
		temp1[0]=a3*a3*0.75-2.0*a2-2.0*temp2[0];
		temp1[1]=                 -2.0*temp2[1];
		Sqrt(temp1,E);
	}

	roots[0][0]=-a3/4.0+R[0]/2.0+D[0]/2.0;
	roots[0][1]=        R[1]/2.0+D[1]/2.0;

	roots[1][0]=-a3/4.0+R[0]/2.0-D[0]/2.0;
	roots[1][1]=        R[1]/2.0-D[1]/2.0;

	roots[2][0]=-a3/4.0-R[0]/2.0+E[0]/2.0;
	roots[2][1]=       -R[1]/2.0+E[1]/2.0;

	roots[3][0]=-a3/4.0-R[0]/2.0-E[0]/2.0;
	roots[3][1]=       -R[1]/2.0-E[1]/2.0;
	return 4;
}
void Term() {
  SignedFactor();
  while(Look == '*' || Look == '/') {
    EmitLn("push rax");
    switch(Look) {
    case '*' : Multiply();break;
    case '/' : Divide();break;
    }
  }
}
Beispiel #12
0
int main()
{
    LinkList l,la,lb,lc;
    l=CreateList(7);
    la=CreateList2(0); lb=CreateList2(0); lc=CreateList2(0);
    Output(l);
    Divide(l,la,lb,lc);

    return 0;
}
Beispiel #13
0
/// <summary>
/// Overloaded operator (/=) for solving the following equation:  value1 /= value2
/// </summary>
/// <param name="src">Large Integer value wich represet value2</param>
/// <returns>Return in the value1 result of operation</returns>
CLargeInteger CLargeInteger::operator /= (const CLargeInteger &src)
{
    CLargeInteger tmp(*this);

    Init();
    
    Divide( &tmp, &src, this);

    return *this;
}
void QuickMedium(T* &vector, int ini, int fin){
  if (fin-ini == 1){
    if (vector[ini]>vector[fin]) Swap(vector[ini], vector[fin]);
  }
  else if (fin-ini > 1){
    int division = Divide(vector, ini, fin);
    SlowMedium(vector, ini, division-1);
    SlowMedium(vector, division+1, fin);
  }
}
Beispiel #15
0
// Divide this surface into two surfaces in
// S direction if bS is true,	u = (m_fS[0]+m_fS[1])/2
// T direction if bS is false,	u = (m_fT[0]+m_fT[1])/2
bool MH_SrfBezier::DivideHalf(bool bS, MH_SrfBezier& bezier1, MH_SrfBezier& bezier2) const
{
	float u;
	if(bS)
		u = (m_fS[0]+m_fS[1])/2.0f;
	else
		u = (m_fT[0]+m_fT[1])/2.0f;

	return Divide(bS, u, bezier1, bezier2);
}
Beispiel #16
0
Maze :: Maze()
{
  numRows = 21;
  numCols = 32;
  grid = new char*[numRows];
  for(int i = 0; i < numRows; i++)
    grid[i] = new char[numCols];
  /*
  strcpy (grid[0], "###############################");
  strcpy (grid[1], "#O#     #             #   #   #");
  strcpy (grid[2], "# # ### ##### # ##### ### # ###");
  strcpy (grid[3], "# # # #     # #     #   #     #");
  strcpy (grid[4], "# # # # # # ### ### ### # ### #");
  strcpy (grid[5], "# # #   # #   #   #   #     # #");
  strcpy (grid[6], "# # # ### ### ####### ##### # #");
  strcpy (grid[7], "#   # #     # #       #   # # #");
  strcpy (grid[8], "########### # # ######### # ###");
  strcpy (grid[9], "#           # # #   #         #");
  strcpy(grid[10], "# # # ####### # # # # # ##### #");
  strcpy(grid[11], "# # #   #   #   # # # # #     #");
  strcpy(grid[12], "### ### # # ##### ### # #######");
  strcpy(grid[13], "#   # # # #     #     # #   # #");
  strcpy(grid[14], "# # # # # # ############# # # #");
  strcpy(grid[15], "# # #   # #             # #   #");
  strcpy(grid[16], "# # ##### ##### ####### # #####");
  strcpy(grid[17], "# #     # #     #     #   #   #");
  strcpy(grid[18], "# ####### # ### # ### ##### # #");
  strcpy(grid[19], "#         #   #     #       #X#");
  strcpy(grid[20], "###############################");
  */
  for(int g = 0; g < 21; g++)
    {
      grid[g][0] = '#';
      grid[g][30] = '#';
    }
  for(int h = 0; h < 31; h++)
    {
      grid[0][h] = '#';
      grid[20][h] = '#';
    }
  for(int m = 1; m < 20; m++)
    for(int n = 1; n < 30; n++)
      grid[m][n] = ' ';

  srand(time(NULL));
  Divide(0, 20, 0, 30);

  endRow = 19;
  endCol = 29;
  currentRow = 1;
  currentCol = 1;
  
  grid[1][1] = 'O';
  grid[19][29] = 'X';
}
Beispiel #17
0
void macro6(){

    auto sig_h=new TH1F("sig_h","Signal Histo",50,0,10);
    auto gaus_h1=new TH1F("gaus_h1","Gauss Histo 1",30,0,10);
    auto gaus_h2=new TH1F("gaus_h2","Gauss Histo 2",30,0,10);
    auto bkg_h=new TH1F("exp_h","Exponential Histo",50,0,10);

    // simulate the measurements
    TRandom3 rndgen;
    for (int imeas=0;imeas<4000;imeas++){
        bkg_h->Fill(rndgen.Exp(4));
        if (imeas%4==0) gaus_h1->Fill(rndgen.Gaus(5,2));
        if (imeas%4==0) gaus_h2->Fill(rndgen.Gaus(5,2));
        if (imeas%10==0)sig_h->Fill(rndgen.Gaus(5,.5));}

    // Format Histograms
    int i=0;
    for (auto hist : {sig_h,bkg_h,gaus_h1,gaus_h2})
        format_h(hist,1+i++);

    // Sum
    auto sum_h= new TH1F(*bkg_h);
    sum_h->Add(sig_h,1.);
    sum_h->SetTitle("Exponential + Gaussian;X variable;Y variable");
    format_h(sum_h,kBlue);

    auto c_sum= new TCanvas();
    sum_h->Draw("hist");
    bkg_h->Draw("SameHist");
    sig_h->Draw("SameHist");

    // Divide
    auto dividend=new TH1F(*gaus_h1);
    dividend->Divide(gaus_h2);

    // Graphical Maquillage
    dividend->SetTitle(";X axis;Gaus Histo 1 / Gaus Histo 2");
    format_h(dividend,kOrange);
    gaus_h1->SetTitle(";;Gaus Histo 1 and Gaus Histo 2");
    gStyle->SetOptStat(0);

    TCanvas* c_divide= new TCanvas();
    c_divide->Divide(1,2,0,0);
    c_divide->cd(1);
    c_divide->GetPad(1)->SetRightMargin(.01);
    gaus_h1->DrawNormalized("Hist");
    gaus_h2->DrawNormalized("HistSame");

    c_divide->cd(2);
    dividend->GetYaxis()->SetRangeUser(0,2.49);
    c_divide->GetPad(2)->SetGridy();
    c_divide->GetPad(2)->SetRightMargin(.01);
    dividend->Draw();
}
Beispiel #18
0
void Divide(int s, int t, edge **L, edge **R) {
	edge *a, *b, *c, *ll, *lr, *rl, *rr, *tangent;
	int n = t - s + 1;
	if (n == 2) *L = *R = Make_edge(Q[s], Q[t]);
	else if (n == 3) {
		a = Make_edge(Q[s], Q[s + 1]), b = Make_edge(Q[s + 1], Q[t]);
		Splice(a, b, Q[s + 1]);
		double v = C3(Q[s], Q[s + 1], Q[t]);
		if (v > eps)       c = Join(a, Q[s], b, Q[t], 0), *L = a, *R = b;
		else if (v < -eps) c = Join(a, Q[s], b, Q[t], 1), *L = c, *R = c;
		else *L = a, *R = b;
	} else if (n > 3) {
		int split = (s + t) / 2;
		Divide(s, split, &ll, &lr); Divide(split + 1, t, &rl, &rr);
		Merge(lr, Q[split], rl, Q[split + 1], &tangent);
		if (Oi(tangent) == Q[s]) ll = tangent;
		if (Dt(tangent) == Q[t]) rr = tangent;
		*L = ll; *R = rr;
	}
}
void Term1() {
  NewLine();
  while(Look == '*' || Look == '/') {
    Push();
    switch(Look) {
      case '*': Multiply(); break;
      case '/': Divide(); break;
    }
    NewLine();
  }
}
Beispiel #20
0
int LimitedKnapsack(std::vector<int> c, std::vector<int> w, int B, std::vector<int> n){
	std::vector<int> new_c, new_w;
	for (int i = 0; i < n.size(); ++i)
	{
		std::vector<int> d = Divide(n[i]);
		for(auto l : d){
			new_c.push_back(l*c[i]);
			new_w.push_back(l*w[i]);
		}
	}
	return knapsack(new_c,new_w,B);
}
Beispiel #21
0
void vMem_Init(FreeSpace* pt_firstFSDescriptor)
{
	uint32_t nbPagesFree;
	uint32_t mod;
	Divide(	(HEAP_END-HEAP_BEG),
			PAGE_SIZE,
			&nbPagesFree,&mod);
	
	(*pt_firstFSDescriptor).nbPagesFree = nbPagesFree;
	(*pt_firstFSDescriptor).addrSpace = (uint32_t*)HEAP_BEG;
	(*pt_firstFSDescriptor).ptNextFreeSpace = pt_firstFSDescriptor;
}
Beispiel #22
0
//4. (Define) Function
int main (int argc, char *argv[]){
	ULong firstNumber;
	ULong secondNumber;
	ULong quotient;
	ULong remainder;

	Input(&firstNumber, &secondNumber);
	Divide(firstNumber, secondNumber, &quotient, &remainder);
	Output(quotient, remainder);

	return 0;
}
Beispiel #23
0
float M2MFstAligner::maximization( bool lastiter ){
  //Maximization. Standard approach is simple count normalization.  
  //The 'penalize' option penalizes links by total length.  Results seem to be inconclusive.
  //  Probably get an improvement by distinguishing between gaps and insertions, etc.
  bool cond = false;
  float change = abs(total.Value()-prevTotal.Value());
  if( cond==false ){
    map<LogArc::Label,LogWeight>::iterator it;
    //cout << "Total: " << total << " Change: " << abs(total.Value()-prevTotal.Value()) << endl;
    prevTotal = total;

    //Normalize and iterate to the next model.  We apply it dynamically 
    // during the expectation step.
    for( it=prev_alignment_model.begin(); it != prev_alignment_model.end(); it++ ){
      alignment_model[(*it).first] = Divide((*it).second,total);
      (*it).second = LogWeight::Zero();
    }
  }else{
    _conditional_max( true );
  }

 
  for( unsigned int i=0; i<fsas.size(); i++ ){
    for( StateIterator<VectorFst<LogArc> > siter(fsas[i]); !siter.Done(); siter.Next() ){
      LogArc::StateId q = siter.Value();
      for( MutableArcIterator<VectorFst<LogArc> > aiter(&fsas[i], q); !aiter.Done(); aiter.Next() ){
	LogArc arc = aiter.Value();
	if( penalize_em==true ){
	  LabelDatum* ld = &penalties[arc.ilabel];
	  if( ld->lhs>1 && ld->rhs>1 ){
	    arc.weight = 99; 
	  }else if( ld->lhsE==false && ld->rhsE==false ){
	    arc.weight = arc.weight.Value() * ld->tot;
	  }
	  /*
	    else{
	    arc.weight = arc.weight.Value() * (ld->tot+10);
	  }
	  */
	  if( arc.weight == LogWeight::Zero() || arc.weight != arc.weight )
	    arc.weight = 99;
	}else{
	  arc.weight = alignment_model[arc.ilabel];
	}
	aiter.SetValue(arc);
      }
    }
  }

  total = LogWeight::Zero();
  return change;
}
Beispiel #24
0
void Term (){
   Factor();
   EmitLn("MOVE D0,-(SP)");
   while (Look[0] == '*' || Look[0] == '/'){
      switch (Look[0]){
         case '*': Multiply();
              break;
         case '/': Divide();
              break;
         default: Expected("Mulop");
      }
   }
}
Beispiel #25
0
void pk (int v[], int p, int inf, int sup, int k){
  int pivote, pivote_sup, pivote_inf;
  int li=0;
  int ls=LVECT-1;



  while(p>=0){
    pivote=Divide(v, li, ls); 
    if((inf<=pivote)&&(pivote<=sup) && (k!= pivote)){ /*Caso 1: Dentro del rango*/

      if(pivote==inf)
	li=pivote+1;

      else if(pivote==sup)
	ls=pivote-1;

      else{
	pivote_inf=Divide(v, li, pivote-1); /*Búsqueda por abajo*/
	pivote_sup=Divide(v, pivote+1, ls); /*Búsqueda por arriba*/

	if(inf>pivote_inf)
	  li=pivote_inf;
	if(sup<pivote_sup)
	  ls=pivote_sup;
      }
      p--;
    }

    if(pivote>sup){/*Caso 2: Fuera del rango, por arriba*/
      ls=pivote-1;
    }

    if(pivote<inf){/*Caso 3: Fuera del rango, por abajo*/
      li=pivote+1;
    }
  }
}
Beispiel #26
0
void VQ_target_vec_norm(Ipp16s gain, Ipp16s nlsgain, Ipp16s* target, Ipp16s* nlstarget){
   Ipp16s tmp, nlstmp, nls;
   Ipp32s k, aa0;

   Divide(16384, 14, gain, nlsgain, &tmp, &nlstmp);
   for(k=0; k<IDIM; k++) {
      aa0 = tmp * target[k];
      target[k] = ShiftR_32s(aa0, 15);
   }
   *nlstarget = 2 + (nlstmp - 15);
   Vscale_16s(target,IDIM, IDIM, 14, target, &nls);
   *nlstarget = (*nlstarget) + nls;
   return;
}
Beispiel #27
0
int InsereInterno(struct No *N, Chave chave, int p, int *itemPromovido, struct No **filhoDItemPromovido, int * valorAssociadoPromovido, int *x)
{
	//Se for um nó nulo, insere na página pai
	if(N == NULL)
	{
		*itemPromovido = chave;
		*valorAssociadoPromovido = p;
		*filhoDItemPromovido = NULL;
		*x = 1;
		return PROMOVE;
	}

	//Senão, procura o ponto i onde "chave" deveria estar na página atual
	int i;
	for(i = 0; i < N->numElementos && chave > N->valoresAssociados[i]; i++);

	//Se a chave já estiver na página, retorna
	if(i < N->numElementos && chave == N->valoresAssociados[i] )
	{
		printf("ERRO, item ja existente\n");
		return CHAVE_JA_EXISTE;
	}
	//Senão, manda inserir na página filha adequada
	int retorno = InsereInterno(N->Filho[i], chave, p, itemPromovido, filhoDItemPromovido, valorAssociadoPromovido, x);

	//Se nenhum item for promovido da página filha, retorna
	if(retorno == NAO_PROMOVE || retorno == CHAVE_JA_EXISTE)
		return retorno;

	//Se um item for promovido e houver espaço nesta página
	if(N->numElementos < ORDEM-1)
	{
		int pos = i;
		for(i = N->numElementos; i > pos; i--)
		{
			N->chaves[i] = N->chaves[i-1];
			N->valoresAssociados[i] = N->valoresAssociados[i-1];
			N->Filho[i+1] = N->Filho[i];
		} 
		N->valoresAssociados[pos] = *valorAssociadoPromovido;
		N->Filho[pos+1] = *filhoDItemPromovido;
		N->chaves[pos] = *itemPromovido;
		N->numElementos++;
		return NAO_PROMOVE;
	}
	//Se não houver espaço, faz a divisão de página
	//itemPromovido será o pivô e filhoDItemPromovido será a nova página, o pivô será inserido na página pai
	Divide(N, itemPromovido, filhoDItemPromovido, valorAssociadoPromovido);
	return PROMOVE; 
}
Beispiel #28
0
LispObject* PowerFloat(LispObject* int1, LispObject* int2, LispEnvironment& aEnvironment,int aPrecision)
{
    if (int2->Number(aPrecision)->iNumber->iExp != 0)
        throw LispErrNotInteger();

    // Raising to the power of an integer can be done fastest by squaring
    // and bitshifting: x^(a+b) = x^a*x^b . Then, regarding each bit
    // in y (seen as a binary number) as added, the algorithm becomes:
    //
    ANumber x(*int1->Number(aPrecision)->iNumber);
    ANumber y(*int2->Number(aPrecision)->iNumber);
    bool neg = y.iNegative;
    y.iNegative=false;

    // result <- 1
    ANumber result("1",aPrecision);
    // base <- x
    ANumber base(aPrecision);
    base.CopyFrom(x);

    ANumber copy(aPrecision);

    // while (y!=0)
    while (!y.IsZero())
    {
        // if (y&1 != 0)
        if ( (y[0] & 1) != 0)
        {
            // result <- result*base
            copy.CopyFrom(result);
            Multiply(result,copy,base);
        }
        // base <- base*base
        copy.CopyFrom(base);
        Multiply(base,copy,copy);
        // y <- y>>1
        BaseShiftRight(y,1);
    }

    if (neg)
    {
        ANumber one("1",aPrecision);
        ANumber dummy(10);
        copy.CopyFrom(result);
        Divide(result,dummy,one,copy);
    }

    // result
    return FloatToString(result, aEnvironment);
}
Beispiel #29
0
// Create, Draw and fit a TGraph2DErrors
void macro4(){
   gStyle->SetPalette(57);
   const double e = 0.3;
   const int nd = 500;

   TRandom3 my_random_generator;
   TF2 f2("f2",
          "1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",
          -6,6,-6,6);
   f2.SetParameters(1,1);
   TGraph2DErrors dte(nd);
   // Fill the 2D graph
   double rnd, x, y, z, ex, ey, ez;
   for (Int_t i=0; i<nd; i++) {
      f2.GetRandom2(x,y);
      // A random number in [-e,e]
      rnd = my_random_generator.Uniform(-e,e);
      z = f2.Eval(x,y)*(1+rnd);
      dte.SetPoint(i,x,y,z);
      ex = 0.05*my_random_generator.Uniform();
      ey = 0.05*my_random_generator.Uniform();
      ez = fabs(z*rnd);
      dte.SetPointError(i,ex,ey,ez);
   }
   // Fit function to generated data
   f2.SetParameters(0.7,1.5);  // set initial values for fit
   f2.SetTitle("Fitted 2D function");
   dte.Fit(&f2);
   // Plot the result
   auto c1 = new TCanvas();
   f2.SetLineWidth(1);
   f2.SetLineColor(kBlue-5);
   TF2   *f2c = (TF2*)f2.DrawClone("Surf1");
   TAxis *Xaxis = f2c->GetXaxis();
   TAxis *Yaxis = f2c->GetYaxis();
   TAxis *Zaxis = f2c->GetZaxis();
   Xaxis->SetTitle("X Title"); Xaxis->SetTitleOffset(1.5);
   Yaxis->SetTitle("Y Title"); Yaxis->SetTitleOffset(1.5);
   Zaxis->SetTitle("Z Title"); Zaxis->SetTitleOffset(1.5);
   dte.DrawClone("P0 Same");
   // Make the x and y projections
   auto c_p= new TCanvas("ProjCan",
                         "The Projections",1000,400);
   c_p->Divide(2,1);
   c_p->cd(1);
   dte.Project("x")->Draw();
   c_p->cd(2);
   dte.Project("y")->Draw();
}
Beispiel #30
0
void pk (int v[], int p, int inf, int sup, int k){
  /*algoritmo p-k*/
  int pivote, li, ls, low, up;
  int i=0;
  li=0;
  ls=LVECT-1;
  low=k-inf;
  up=sup-k;


  pivote=Divide(v, li, ls); 

  while(res[sup-inf-1]<0){

    if((inf<=pivote)&&(pivote<=sup) ){
      res[i]=v[pivote];
      i++;
      pivote=Divide(v, li, pivote-1);
      pivote=Divide(v, pivote+1, ls);
    }

    if(pivote>=sup){
      ls=pivote -1;
      pivote=Divide(v, li, ls); 
    }

    if(pivote<=inf){
      li=pivote +1;
      pivote=Divide(v, li, ls); 
    }
  }

  printf("\n===RESULTADO===\n");
  printvec(res, sup-inf);
  printf("\n");
}