Ejemplo n.º 1
0
int main(void) {
  printf("Nullstelle [2, 4], eps=10^-8: %f\n", bisection(2, 4, 10e-8));
  printf("Nullstelle [4, 6], eps=10^-2: %f\n", bisection(4, 6, 10e-2));
  printf("Nullstelle [6, 8], eps=10^-8: %f\n", bisection(6, 8, 10e-8));
  
  return 0;
}
Ejemplo n.º 2
0
double bisection (double xl, double xr, double tolerance, double func()) {
	double d = (xl + xr) / 2, f = (*func)(d);
	if (fabs(f) <= tolerance) return d;
	if (sign(f) == sign((*func)(xl)))
		return bisection(d, xr, tolerance, func);
	return bisection(xl, d, tolerance, func);
}
Stokhos::KL::OneDExponentialCovarianceFunction<value_type>::
OneDExponentialCovarianceFunction(int M, 
				  const value_type& a, 
				  const value_type& b, 
				  const value_type& L_,
				  const std::string& dim_name,
				  Teuchos::ParameterList& solverParams) :
  L(L_),
  eig_pair(M)
{
  // Get parameters with default values
  magnitude_type eps = solverParams.get("Bound Perturbation Size", 1e-6);
  magnitude_type tol = solverParams.get("Nonlinear Solver Tolerance", 1e-10);
  int max_it = solverParams.get("Maximum Nonlinear Solver Iterations", 100);

  value_type aa, alpha, omega, lambda;
  int i=0;
  double pi = 4.0*std::atan(1.0);
  int idx = 0;
  
  aa = (b-a)/2.0;
  while (i < M-1) {
    alpha = aa/L;
    omega = bisection(EigFuncCos(alpha), idx*pi, idx*pi+pi/2.0-eps, 
		      tol, max_it) / aa;
    lambda = 2.0*L/(L*L*omega*omega + 1.0);
    eig_pair[i].eig_val = lambda;
    eig_pair[i].eig_func = Teuchos::rcp(new 
      ExponentialOneDEigenFunction<value_type>(
	ExponentialOneDEigenFunction<value_type>::COS, a, b, omega, dim_name)
      );
    i++;

    omega = bisection(EigFuncSin(alpha), idx*pi+pi/2.0+eps, (idx+1)*pi,
		      tol, max_it) / aa;
    lambda = 2.0*L/(L*L*omega*omega + 1.0);
    eig_pair[i].eig_val = lambda;
    eig_pair[i].eig_func = Teuchos::rcp(new
      ExponentialOneDEigenFunction<value_type>(
	ExponentialOneDEigenFunction<value_type>::SIN, a, b, omega, dim_name)
      );
    i++;

    idx++;
  }
  if (i < M) {
    omega = bisection(EigFuncCos(alpha), idx*pi, idx*pi+pi/2.0-eps, 
		      tol, max_it) / aa;
    lambda = 2.0*L/(L*L*omega*omega + 1.0);
    eig_pair[i].eig_val = lambda;
    eig_pair[i].eig_func = Teuchos::rcp(new
      ExponentialOneDEigenFunction<value_type>(
	ExponentialOneDEigenFunction<value_type>::COS, a, b, omega, dim_name)
      );
  }
}
Ejemplo n.º 4
0
int main() {
	double xl = -100.0, xr = 100.0, t = 0.0000001;
	puts("\nTest 1: x^3 = 0.");
	printf("xl = %f; xr = %f; tolerance = %f\n", -100.0, 150.0, t);
	printf("Bisection: x = %f\n", bisection(-100.0, 150.0, t, &cube));
	printf("xl = %f; xr = %f; tolerance = %f\n", -0.001, 0.001, t);
	printf("Secant: x = %f\n", secant(-0.001, 0.001, t, &cube));
	puts("\nTest 2: Matrix test (x^j = 10^i).");
	for(j = 1; j < 10; j++) for(i = 1; i < 10; i++) {
		printf("j = %f; i = %f\n", j, i);
		printf("Bisection: x = %f\n", bisection(xl, xr, t, &poly));
		printf("Secant: x = %f\n", secant(xl, xr, t, &poly));
	}
}
Ejemplo n.º 5
0
void bisection(double value, double* heap,int hi,int lo){
	int middle = (hi+lo)/2;
	if (middle == hi || middle == lo){
		printf("Found it between elements %d %d\n These have values %f %f\n",lo,hi, heap[lo],heap[hi]); 
		return;
	}
	if(heap[middle]<value){
		//printf("Go into %d to %d\n", middle,hi );
		bisection(value,heap,hi,middle);
	}else{
		//printf("Go into %d to %d\n", lo,middle );
		bisection(value,heap,middle,lo);
	}
     
}
Ejemplo n.º 6
0
Archivo: zad2.cpp Proyecto: mskiba/MO
int main() {
  double a, b, e;
  int status; 
  char chce_podac_x[2];
  do {
    printf("Podaj a: ");
    scanf("%lf", &a);
    printf("Podaj b: ");
    scanf("%lf", &b);
    if(a < b) {
      if (f(a) * f(b) < 0) {
        do {
          printf("Podaj przybliżenie: ");
          status = scanf("%lf", &e);
          if(e > 0 && e < 1) {
            bisection(a, b, e);
            newton(a, e);
          }
          do {
            printf("Chcesz podać kolejne przybliżenie? (tak/nie): ");
            scanf("%s", chce_podac_x);
            if(strcmp(chce_podac_x, "tak") == 0 || strcmp(chce_podac_x, "nie") == 0) break;
          } while(1);
        } while (strcmp(chce_podac_x, "tak") == 0);	
      } else {
        printf("błąd: f(a) i f(b) muszą mieć różny znak\n");
      }	
    } else {
      printf("błąd: a musi być mniejsze od b\n");
    }
  } while(a >= b || f(a) * f(b) >= 0);

  return 0;
}
Ejemplo n.º 7
0
double 	PieceWiseConstant::operator() (double x) const {
	if (x<xs[lastPos]) {
		if (lastPos == 0)
			return ys[0];	// the first one	//	x < xs[0]
		else if (x>xs[lastPos-1])		// xs[lp-1] 	x < xs[lp]
			return ys[lastPos];		
		else					// x	< xs[lp-1] < xs[lp]
			return bisection(x);
		
	} else if (x > xs[n-1]){
		std::cout << "x=" << x << std::endl;
		std::cout << "xs[n-1]=" << xs[n-1] << std::endl;			// check if x is reasonable
		throw("too big than the largest in pieceswiseconstant");
	} else		// bisection
		return bisection(x);
}
Ejemplo n.º 8
0
int main(int argc, char **argv){
	int order;
	printf("How many random numbers: 10^");
	scanf("%d",&order);
	int size =(int)pow(10,order);
	double* heap = calloc(size,sizeof(double*));
	srand(time(NULL));
	for(int i = 1; i<size ;i++){
	    double R =(rand()/(RAND_MAX+1.0));
	    heap[i] = R;
	    //printf("%f\n",R);
	}

    heapsort(heap,size);
	for(int i = 1; i<6 ;i++){
		printf("%f \n",heap[i] );
	}
	printf(".........\n");
	for(int i = size-7; i<size-1 ;i++){
		printf("%f \n",heap[i] );
	}
    bisection(.7,heap,size,0);
    printf("Number of operations: ");
    num_ops();
	return 0;
}
Ejemplo n.º 9
0
//---------------------------------------------------------------------------
double TfrmCalcParameter::BetaFunction(double* TT, int* day,int ndays,double cover1p, int GrowthZero, double Wmax,double *tm)
{
  double t0=thermalDAP1(TT,day,cover1p,ndays);
  double te=thermalDAP1(TT,day,GrowthZero,ndays);
  *tm = bisection(0, te + 10,Wmax,te,t0);
  return te;
}
Ejemplo n.º 10
0
int main()
{
  printf("\n   Dla  równania  f(x) = 0,  gdzie  f(x) = 3x + 2 - e^x,  wczytać  a, b  należące");
  printf("\n   do zbioru liczb rzeczywistych takie, by a < b oraz f(a) * f(b) < 0. Następnie,");
  printf("\n   dopóki  \"użytownik się nie znudzi\",  wczytywać  wartości  0 < E < 1  i  metodą");
  printf("\n   połowienia  na  [a, b]  przybliżyc z dokładnością E rozwiązanie tego równania.");
  printf("\n   Rozwiązanie to przybliżyc również metodą Newtona  z  x_0 = a,  przy czym,  x_k");
  printf("\n   będzie  dobrym   przybliżeniem,  gdy  |x_k - x_(k - 1)| <= E.  Porównać  ilość");
  printf("\n   kroków wykonanych metodą połowienia i metodą Newtona.\n");

  double a, b;

  printf("\n   Podaj a należące do zbioru liczb rzeczywistych:\n   a = ");
  scanf("%lf", &a);

  b = a;

  while(a >= b || equation(a) * equation(b) >= 0)
  {
    printf("\n   Podaj b należące do zbioru liczb rzeczywistych,\n   takie by b > a oraz f(b) * f(a) < 0\n   b = ");
    scanf("%lf", &b);
  }

  double epsilon, rB, rN;
  int choice;

  while (1)
  {
    printf("\n   1 - Przybliż rozwiązanie równania z dokładnością E metodą połowienia i Newtona");
    printf("\n   2 - Zakoncz program");
    printf("\n   Twoj wybor: ");
    scanf("%i", &choice);

    switch (choice)
    {
      case 1:
        epsilon = 0;

        while (epsilon <= 0 || epsilon >= 1)
        {
          printf("\n   Podaj E, takie by 0 < E < 1:\n   E = ");
          scanf("%lf", &epsilon);
        }

        rB = bisection(a, b, epsilon);
        rN = newton(a, epsilon);

        printf("\n   Metoda połowienia:\n   %lf - przybliżone rozwiązanie\n   %i - ilość kroków\n", rB, iB);
        printf("\n   Metoda Newtona:\n   %lf - przybliżone rozwiązanie\n   %i - ilość kroków\n", rN, iN);

        iB = iN = 0;

        break;

      case 2:
        printf("\n");
        return 0;
    }
  }
}
Ejemplo n.º 11
0
double bisection(double (*func)(double), double x_l , double x_r){
    //make sure x's always bracket root
    if(bracketed((*func)(x_l), (*func)(x_r))){
        //return when four digits or precision are recieved
        if(fabs(x_r - x_l) < (1/pow(10.0,4.0))){return (x_l + x_r)/2.0; }
        double x_n = (x_r + x_l)/2.0;
        //reccur
        if(bracketed( (*func)(x_l), (*func)(x_n) )){
            bisection((*func), x_l, x_n);
        }else{
            bisection((*func), x_n, x_r);
        }

    }else{
        printf("Something went wrong no longer bracketed\n");
        return 0.0;
    }


}
Ejemplo n.º 12
0
int main(){
        
    while( scanf("%lf %lf %lf %lf %lf %lf", &p, &q, &r, &s, &t, &u ) != EOF ){
	
		if( f(0.0)*f(1.0) > 0.0 ) puts( "No solution" );
		else printf( "%.4lf\n", bisection() );
              
    }          
       
    return 0;
}
Ejemplo n.º 13
0
/**
 * Finds root in the interval \f$ [t1,t2] \f$.
 */
int RootFinder::solve(double t1, double t2, double* root) {
    switch(method) {
	case BISECTION: 
	    return bisection(t1, t2, root);
	case BRENTS_METHOD: 
	    return brents_method(t1, t2, root);
	case REGULA_FALSI: 
	    return regula_falsi(t1, t2, root);
        default: 
	    return false;			    
    }
}
Ejemplo n.º 14
0
int main()
{
    //freopen("out.txt","w",stdout);
    //a and b are the left and right end points
    double a,b;

    a = 0.14;
    b = 0.16;
    bisection(a,b);

    return 0;
}
Ejemplo n.º 15
0
 double bisection ( // finds root f_(x_) = y_ in [p_, q_]
 double y_, // f_ (x_) = y_
 double (*f_) (double x_), // function 
 double p_, // end-point
 double q_, // end-point
 double tol_, // absolute tolerance
 double rtol_, // relative tolerance
 Int4 *itmax_) // maximum # of permitted iterations
 {
    s_f = f_;
    return bisection (y_, f, ZERO, p_, q_, tol_, rtol_, itmax_);
 }
int main(int argc,char *argv[]) {
  double a,b;

  if (argc != 3) {
    fprintf(stderr,"%s <a> <b>\n",argv[0]);
    exit(1);
  }
  a = atof(argv[1]);
  b = atof(argv[2]);
  bisection(f,a,b,100,1.0e-7);
  exit(0);
}
Ejemplo n.º 17
0
int main(){
	long n;
	int test, kase;
	
	while( scanf("%d", &test) == 1 ){
		for ( kase = 1 ; kase <= test ; kase++ ){
			scanf("%ld", &n);
			printf("Case %d: ", kase);
			n = bisection(n);
			if ( n < 0 ) puts("impossible");
			else printf("%ld\n", n);
		}
	}
	
	return 0;
}
Ejemplo n.º 18
0
real robust(real a, real b,
	    fctptr const f, fctptr const df,
	    real const & tol, real const & cfratio, 
	    int const & maxit, checkT const & check,
	    int & nit_coarse, int & nit_fine )
{
  // Call bisection method (with a greater desired tolerance)
  real tol_bis = cfratio * tol;
  real x_bis = bisection(a, b, f, tol, maxit, check, nit_coarse);

  /*
    Call a Newton algorithm which uses as an initial value
    the solution given by bisection method
  */
  return newton(x_bis, f, df, tol, maxit, check, nit_fine);
}
Ejemplo n.º 19
0
int sub_iso(std::set<traverse_history_t> A, Graph *Gl) {
	if(Gl->get_nodes().size() < (*(A.begin())).size())
		return 0;
		
	int num_of_subisomorphisms = 0;
	
	Graph *g1 = new Graph();
	Graph *g2 = new Graph();
	
	bisection(Gl, g1, g2);
	
	/*printf("~~~~~~G1~~~~~~~~\n");
	g1->print();
	printf("\n");
	
	printf("~~~~~~G2~~~~~~~~\n");
	g2->print();
	*/
	
	for(std::vector<Node *>::iterator it1 = g1->get_nodes().begin(); it1 != g1->get_nodes().end(); it1++) {
		for(std::vector<Node *>::iterator it2 = g2->get_nodes().begin(); it2 != g2->get_nodes().end(); it2++) {
			if((*it1)->is_connected(*it2)) {
				for(std::set<traverse_history_t>::iterator it3 = A.begin(); it3 != A.end(); it3++){
					std::vector<Graph *> S = search_traverse(Gl, *it1, *it2, *it3);
					
					num_of_subisomorphisms += S.size();
					
					for(std::vector<Graph *>::iterator it4 = S.begin(); it4 != S.end(); it4++) {
						printf("-----FOUND------------------------------------------\n");
						(*it4)->print();
						printf("----------------------------------------------------\n");
					}
				}
					
				Gl->set_edge_color((*it1)->get_id(), (*it2)->get_id(), false);
				Gl->set_edge_color((*it2)->get_id(), (*it1)->get_id(), false);
			}
		}
	}
	
	num_of_subisomorphisms += sub_iso(A, g1);
	num_of_subisomorphisms += sub_iso(A, g2);
	
	return num_of_subisomorphisms;
}
Ejemplo n.º 20
0
int sweep_bisection(double (*func)(double x),double xstart,double xstop,double xinc,int nmax,double tol) {
  double a,b,fa,fb;
  int retval;

  xstop = xstop + (xinc * 0.5);
  a = xstart;
  fa = (*func)(a);
  b = a + xinc;
  while (((xinc > 0.0) && (b < xstop)) || ((xinc < 0.0) && (b > xstop))) {
    fb = (*func)(b);
    if ((fa * fb) < 0.0) {   /*root bracketed, converge with bisection*/
      retval = bisection(func,a,b,nmax,tol);
      if (retval > 0) return(retval);
    }
    a = b;
    fa = fb;
    b = b + xinc;
  }
  return(0);
}
Ejemplo n.º 21
0
void prox(prob_vars * vars, all_data * data, prox_data * p_data)
{
	memcpy(vars->x_t,vars->x,data->n*(data->T+1)*sizeof(double));
	subArray(vars->x_t,vars->z,data->n*(data->T+1));

	memcpy(vars->u_t,vars->u,data->m*(data->T+1)*sizeof(double));
	subArray(vars->u_t,vars->y,data->m*(data->T+1));

	/* The proximal step using bisection (x_t, u_t) */
	int idx;
	#pragma omp parallel for private(idx)
	for ( int t = 0; t < data->T+1; t++ ) {
		for ( int j = 0; j < p_data->numsource; j++ ) {	
			idx = t*data->m + p_data->idx_source[j];
			/* Saturate the inputs */
			vars->u_t[idx] =  -fminl(-fminl(vars->u_t[idx],p_data->U), 0);
		}

		for ( int i = 0; i < data->n; i++ ){  /* For every node... */
			idx = t*data->n+i;
			bisection(data,&(vars->u_t[t*data->m]), &(vars->x_t[idx]), p_data, i);
		}
	}
}
Ejemplo n.º 22
0
int main()
{
  double a, b, x, y1, y2, h, eps = pow(2.0, -30);
  int n;
  
  printf("初期値[a,b]を入力a b\n");
  scanf("%lf %lf",&a,&b);
  printf("区分nを入力\n");
  scanf("%d",&n);
  
//bisectionを適用//
  h = (b-a)/n;
  y1 = f(a);
  for(x = a + h;a <= b; x += h)
    {
      y2 = f(x);
      if(y1*y2 < 0.0)
	{
	  printf("求める答えはx =%f\n",bisection(x-h, x, eps));
	}
      y1 = y2;
    }
  return 0;
}
Ejemplo n.º 23
0
/* problem:  */
void problem(DomainS *pDomain)
{
  GridS *pG = pDomain->Grid;
  int i,j,k,n,converged;
  int is,ie,il,iu,js,je,jl,ju,ks,ke,kl,ku;
  int nx1, nx2, nx3;
  Real x1, x2, x3;
  Real a,b,c,d,xmin,xmax,ymin,ymax;
  Real x,y,xslow,yslow,xfast,yfast;
  Real R0,R1,R2,rho,Mdot,K,Omega,Pgas,beta,vR,BR,vphi,Bphi;
  ConsS *Wind=NULL;
  Real *pU=NULL,*pUl=NULL,*pUr=NULL;
  Real lsf,rsf;

  is = pG->is;  ie = pG->ie;  nx1 = ie-is+1;
  js = pG->js;  je = pG->je;  nx2 = je-js+1;
  ks = pG->ks;  ke = pG->ke;  nx3 = ke-ks+1;

  il = is-nghost*(nx1>1);  iu = ie+nghost*(nx1>1);  nx1 = iu-il+1;
  jl = js-nghost*(nx2>1);  ju = je+nghost*(nx2>1);  nx2 = ju-jl+1;
  kl = ks-nghost*(nx3>1);  ku = ke+nghost*(nx3>1);  nx3 = ku-kl+1;

#ifndef CYLINDRICAL
  ath_error("[cylwindrotb]: This problem only works in cylindrical!\n");
#endif
#ifndef MHD
  ath_error("[cylwindrotb]: This problem only works in MHD!\n");
#endif

  if (nx1==1) {
    ath_error("[cylwindrotb]: Only R can be used in 1D!\n");
  }
  else if (nx2==1 && nx3>1) {
    ath_error("[cylwindrotb]: Only (R,phi) can be used in 2D!\n");
  }

  /* Allocate memory for wind solution */
  if ((Wind = (ConsS*)calloc_1d_array(nx1+1,sizeof(ConsS))) == NULL)
    ath_error("[cylwindrotb]: Error allocating memory\n");

  /* Allocate memory for grid solution */
  if ((RootSoln = (ConsS***)calloc_3d_array(nx3,nx2,nx1,sizeof(ConsS))) == NULL)
    ath_error("[cylwindrotb]: Error allocating memory\n");

  theta = par_getd("problem","theta");
  omega = par_getd("problem","omega");
  vz    = par_getd("problem","vz");

  /* This numerical solution was obtained from MATLAB.
   * Ideally, we replace this with a nonlinear solver... */
  xslow = 0.5243264128;
  yslow = 2.4985859152;
  xfast = 1.6383327831;
  yfast = 0.5373957134;
  E     = 7.8744739104;
  eta   = 2.3608500383;

  xmin = par_getd("domain1","x1min")/R_A;
  xmax = par_getd("domain1","x1max")/R_A;
  ymin = 0.45/rho_A;
  ymax = 2.6/rho_A;

  printf("theta = %f,\t omega = %f,\t eta = %f,\t E = %f\n", theta,omega,eta,E);
  printf("xslow = %f,\t yslow = %f,\t xfast = %f,\t yfast = %f\n", xslow,yslow,xfast,yfast);
  printf("xmin = %f,\t ymin = %f,\t xmax = %f,\t ymax = %f\n", xmin,ymin,xmax,ymax);


  /* Calculate the 1D wind solution at cell-interfaces */
  for (i=il; i<=iu+1; i++) {
    memset(&(Wind[i]),0.0,sizeof(ConsS));
    cc_pos(pG,i,js,ks,&x1,&x2,&x3);

    /* Want the solution at R-interfaces */
    R0 = x1 - 0.5*pG->dx1;
    x = R0/R_A;

    /* Look for a sign change interval */
    if (x < xslow) {
      sign_change(myfunc,yslow,10.0*ymax,x,&a,&b);
      sign_change(myfunc,b,10.0*ymax,x,&a,&b);
    } else if (x < 1.0) {
      sign_change(myfunc,1.0+TINY_NUMBER,yslow,x,&a,&b);
    } else if (x < xfast) {
      sign_change(myfunc,yfast,1.0-TINY_NUMBER,x,&a,&b);
      if (!sign_change(myfunc,b,1.0-TINY_NUMBER,x,&a,&b)) {
        a = yfast;
        b = 1.0-TINY_NUMBER;
      }
    } else {
      sign_change(myfunc,0.5*ymin,yfast,x,&a,&b);
    }

    /* Use bisection to find the root */
    converged = bisection(myfunc,a,b,x,&y);
    if(!converged) {
      ath_error("[cylwindrotb]:  Bisection did not converge!\n");
    }

    /* Construct the solution */
    rho = rho_A*y;
    Mdot = sqrt(R_A*SQR(rho_A)*GM*eta);
    Omega = sqrt((GM*omega)/pow(R_A,3));
    K = (GM*theta)/(Gamma*pow(rho_A,Gamma_1)*R_A);
    Pgas = K*pow(rho,Gamma);
    vR = Mdot/(R0*rho);
    beta = sqrt(1.0/rho_A);
    BR = beta*rho*vR;
    vphi = R0*Omega*(1.0/SQR(x)-y)/(1.0-y);
    Bphi = beta*rho*(vphi-R0*Omega);

    Wind[i].d   = rho;
    Wind[i].M1  = rho*vR;
    Wind[i].M2  = rho*vphi;
    Wind[i].M3  = rho*vz;
    Wind[i].B1c = BR;
    Wind[i].B2c = Bphi;
    Wind[i].B3c = 0.0;
    Wind[i].E   = Pgas/Gamma_1
      + 0.5*(SQR(Wind[i].B1c) + SQR(Wind[i].B2c) + SQR(Wind[i].B3c))
      + 0.5*(SQR(Wind[i].M1 ) + SQR(Wind[i].M2 ) + SQR(Wind[i].M3 ))/Wind[i].d;
  }

  /* Average the wind solution across the zone for cc variables */
  for (i=il; i<=iu; i++) {
    memset(&(pG->U[ks][js][i]),0.0,sizeof(ConsS));
    cc_pos(pG,i,js,ks,&x1,&x2,&x3);
    lsf = (x1 - 0.5*pG->dx1)/x1;
    rsf = (x1 + 0.5*pG->dx1)/x1;

    pU  = (Real*)&(pG->U[ks][js][i]);
    pUl = (Real*)&(Wind[i]);
    pUr = (Real*)&(Wind[i+1]);
    for (n=0; n<NWAVE; n++) {
      pU[n] = 0.5*(lsf*pUl[n] + rsf*pUr[n]);
    }

    pG->B1i[ks][js][i]   = Wind[i].B1c;
    pG->B2i[ks][js][i]   = 0.5*(lsf*Wind[i].B2c + rsf*Wind[i+1].B2c);
    pG->B3i[ks][js][i]   = 0.5*(lsf*Wind[i].B3c + rsf*Wind[i+1].B3c);
  }

  /* Copy 1D solution across the grid and save */
  for (k=kl; k<=ku; k++) {
    for (j=jl; j<=ju; j++) {
      for (i=il; i<=iu; i++) {
        pG->U[k][j][i] = pG->U[ks][js][i];
        pG->B1i[k][j][i] = pG->B1i[ks][js][i];
        pG->B2i[k][j][i] = pG->B2i[ks][js][i];
        pG->B3i[k][j][i] = pG->B3i[ks][js][i];
        RootSoln[k][j][i]  = pG->U[ks][js][i];
      }
    }
  }

  StaticGravPot = grav_pot;
  bvals_mhd_fun(pDomain,left_x1,do_nothing_bc);
  bvals_mhd_fun(pDomain,right_x1,do_nothing_bc);

  free_1d_array((void *)Wind);

  return;
}
Ejemplo n.º 24
0
int TTVFast(double *params,double dt, double Time, double total,int n_plan,CalcTransit *transit,CalcRV *RV_struct, int nRV, int n_events, int input_flag)
{
  n_planets=n_plan;
  int  planet;
  int i, j;
  j=0;
  void jacobi_heliocentric(PhaseState *jacobi, PhaseState *helio, double GMsun, double *GM);
  double dot0,dot1,dot2,rskyA,rskyB,vprojA,vprojB,rsky,vproj,velocity,new_dt;
  double compute_RV(PhaseState *ps);
  double compute_deriv(PhaseState ps,int planet);
  int RV_count = 0;
  int k=0;
  double deriv;
  double  dt2 = dt/2.0;

  if(RV_struct !=NULL){
    RV_count = nRV;
  }

  machine_epsilon = determine_machine_epsilon();
  if(input_flag ==0){
    read_jacobi_planet_elements(params);
  }
  if(input_flag ==1){
    read_helio_planet_elements(params);
  }
  if(input_flag ==2){
    read_helio_cartesian_params(params);
  }
  if(input_flag !=0 && input_flag !=1 && input_flag !=2){
    printf("Input flag must be 0,1, or 2. \n");
    //exit(-1);
    return FAILURE;
  }
  
  copy_system(p, rp);
  compute_corrector_coefficientsTO(dt);
  real_to_mapTO(rp, p);

  for(i = 0;i<n_planets;i++){
  prev_dot[i] = p[i].x*p[i].xd+p[i].y*p[i].yd;
  count[i]=0;

  }

  if (A(p, dt2) != SUCCESS)
  	return FAILURE;

  while(Time < total){
    copy_system(p, p_tmp);
    B(p,dt);
    if( A(p,dt) != SUCCESS)
		return FAILURE;
    Time+=dt;
    /* Calculate RV if necessary */

    if(j <RV_count){
      RVTime = Time+dt2;
      
      if(RVTime>(RV_struct+j)->time && RVTime-dt<(RV_struct+j)->time){
	if(RVTime-(RV_struct+j)->time > (RV_struct+j)->time-(RVTime-dt)){
	  copy_system(p_tmp,p_RV);
	  new_dt= (RV_struct+j)->time-(RVTime-dt);
	  if( A(p,dt) != SUCCESS)
		return FAILURE;
	  velocity = compute_RV(p_RV);
	  (RV_struct+j)->RV =velocity;
	  
	}else{
	  copy_system(p,p_RV);
	  new_dt= (RV_struct+j)->time-RVTime;
	  if( A(p,dt) != SUCCESS)
		return FAILURE;
	  velocity = compute_RV(p_RV);
	  (RV_struct+j)->RV =velocity;
	}
	j++;
      }
    }
    
    /* now look for transits */
    
    for(i = 0;i<n_planets;i++){ /* for each planet */
      curr_dot[i] = p[i].x*p[i].xd+p[i].y*p[i].yd;
      curr_z[i] = p[i].z;
      tplanet=i;
      /* Check Transit Condition*/
      if(prev_dot[tplanet]<0 && curr_dot[tplanet]>0 && curr_z[tplanet]>0){
	bad_transit_flag = 0;
	copy_system(p,p_ahead);
	copy_system(p_tmp,p_behind);    
	if (A(p_ahead,-dt2) != SUCCESS)
		return FAILURE ;
	if (A(p_behind,-dt2) !=SUCCESS)
		return FAILURE ;
	jacobi_heliocentric(p_behind,helioBehind,GMsun,GM);	  
	jacobi_heliocentric(p_ahead,helioAhead,GMsun,GM);
	
	/* Calculate Rsky.Vsky */
	dot2 = helioAhead[tplanet].x*helioAhead[tplanet].xd+helioAhead[tplanet].y*helioAhead[tplanet].yd;
	dot1 = helioBehind[tplanet].x*helioBehind[tplanet].xd+helioBehind[tplanet].y*helioBehind[tplanet].yd;
	
	if(dot1 < 0 && dot2 >0){
	  /* If Rsky.Vsky passed through zero*/
	  TimeA=Time;
	  TimeB = Time-dt;
	  dotA= TimeA+kepler_transit_locator(kc_helio[tplanet],-dt,&helioAhead[tplanet],&temporary);

	  deriv = compute_deriv(temporary,tplanet);

	  if(deriv < 0.0 || temporary.z <0.0 || dotA < TimeB-PI/mm[tplanet] || dotA > TimeA+PI/mm[tplanet]){ /* was the right root found?*/
	    dotA= TimeA+bisection(kc_helio[tplanet],&helioAhead[tplanet],&helioBehind[tplanet],&temporary);
	  }
	  
	  rskyA = sqrt(temporary.x*temporary.x + temporary.y*temporary.y);
	  vprojA = sqrt(temporary.xd*temporary.xd + temporary.yd*temporary.yd);
	  
	  dotB= TimeB+kepler_transit_locator(kc_helio[tplanet],dt,&helioBehind[tplanet],&temporary);

	  deriv = compute_deriv(temporary,tplanet);	  

	  if(deriv < 0.0 || temporary.z <0.0 || dotB < TimeB-PI/mm[tplanet] || dotB > TimeA+PI/mm[tplanet]){ /* was the right root found?*/
	    dotB= TimeB+bisection(kc_helio[tplanet],&helioBehind[tplanet],&helioAhead[tplanet],&temporary);
	  }
	  
	  rskyB = sqrt(temporary.x*temporary.x + temporary.y*temporary.y);
	  vprojB = sqrt(temporary.xd*temporary.xd + temporary.yd*temporary.yd);
	  
	  tdot_result = ((dotB-TimeB)*dotA+(TimeA-dotA)*dotB)/(TimeA-TimeB-dotA+dotB);
	  
	  rsky = ((dotB-TimeB)*rskyA+(TimeA-dotA)*rskyB)/(TimeA-TimeB-dotA+dotB);
	  vproj = ((dotB-TimeB)*vprojA+(TimeA-dotA)*vprojB)/(TimeA-TimeB-dotA+dotB);
	}else{
	  
	  copy_system(helioAhead,helioBehind);
	  copy_system(p,p_ahead);
	  B(p_ahead,dt);
	  if (A(p_ahead,dt2) != SUCCESS)
		return FAILURE;
	  TimeA=Time+dt;
	  TimeB = Time;
	  jacobi_heliocentric(p_ahead,helioAhead,GMsun,GM);
	  dotB= TimeB+kepler_transit_locator(kc_helio[tplanet],dt,&helioBehind[tplanet],&temporary);
	  
	  deriv = compute_deriv(temporary,tplanet);	  
	  
	  if(deriv < 0.0 || temporary.z <0.0 || dotB < TimeB-PI/mm[tplanet] || dotB > TimeA+PI/mm[tplanet]){ /* was the right root found?*/
	    dotB= TimeB+bisection(kc_helio[tplanet],&helioBehind[tplanet],&helioAhead[tplanet],&temporary);
	  }
	  
	  rskyB = sqrt(temporary.x*temporary.x + temporary.y*temporary.y);
	  vprojB = sqrt(temporary.xd*temporary.xd + temporary.yd*temporary.yd);
	  
	  dotA= TimeA+kepler_transit_locator(kc_helio[tplanet],-dt,&helioAhead[tplanet],&temporary);
	  
	  deriv = compute_deriv(temporary,tplanet);	  
	  
	  if(deriv < 0.0 || temporary.z <0.0 || dotA < TimeB-PI/mm[tplanet] || dotA > TimeA+PI/mm[tplanet]){ /* was the right root found?*/
	    dotA= TimeA+bisection(kc_helio[tplanet],&helioAhead[tplanet],&helioBehind[tplanet],&temporary);
	  }
	  
	  rskyA = sqrt(temporary.x*temporary.x + temporary.y*temporary.y);
	  vprojA = sqrt(temporary.xd*temporary.xd + temporary.yd*temporary.yd);
	  
	  tdot_result = ((dotB-TimeB)*dotA+(TimeA-dotA)*dotB)/(TimeA-TimeB-dotA+dotB);
	  rsky =  ((dotB-TimeB)*rskyA+(TimeA-dotA)*rskyB)/(TimeA-TimeB-dotA+dotB);
	  vproj =  ((dotB-TimeB)*vprojA+(TimeA-dotA)*vprojB)/(TimeA-TimeB-dotA+dotB);
	}
	if(k< n_events){
	  
	  if(bad_transit_flag ==0){
	    (transit+k)->planet = tplanet;
	    (transit+k)->epoch = count[tplanet];
	    (transit+k)->time = tdot_result;
	    (transit+k)->rsky = rsky;
	    (transit+k)->vsky = vproj;
	  }else{
	    (transit+k)->planet = tplanet;
	    (transit+k)->epoch = count[tplanet];
	    (transit+k)->time = BAD_TRANSIT;
	    (transit+k)->rsky = BAD_TRANSIT;
	    (transit+k)->vsky = BAD_TRANSIT;
	  }
	  count[tplanet]++;
	  k++;
	}else{
	  printf("Not enough memory allocated for Transit structure: more events triggering as transits than expected. Possibily indicative of larger problem.\n");
	  //exit(-1);
	  return FAILURE;
	}
      }
      
      prev_dot[i]=curr_dot[i];      
    }
  }
  return SUCCESS;
}
Ejemplo n.º 25
0
/* problem:  */
void problem(DomainS *pDomain)
{
  GridS *pG = pDomain->Grid;
  int i,j,k;
  int is,ie,il,iu,js,je,jl,ju,ks,ke,kl,ku;
  int nx1,nx2,nx3;
  Real x1,x2,x3;
  Real xs,vs,v,pgas0,pgas,alpha,beta,a,b,converged;

  is = pG->is;  ie = pG->ie;  nx1 = ie-is+1;
  js = pG->js;  je = pG->je;  nx2 = je-js+1;
  ks = pG->ks;  ke = pG->ke;  nx3 = ke-ks+1;

  il = is-nghost*(nx1>1);  iu = ie+nghost*(nx1>1);  nx1 = iu-il+1;
  jl = js-nghost*(nx2>1);  ju = je+nghost*(nx2>1);  nx2 = ju-jl+1;
  kl = ks-nghost*(nx3>1);  ku = ke+nghost*(nx3>1);  nx3 = ku-kl+1;

#ifdef MHD
  ath_error("[cylwindrot]: This problem only works in hydro!\n");
#endif

#ifndef CYLINDRICAL
  ath_error("[cylwindrot]: This problem only works in cylindrical!\n");
#endif

  if (nx1==1) {
    ath_error("[cylwindrot]: This problem can only be run in 2D or 3D!\n");
  }
  else if (nx2==1 && nx3>1) {
    ath_error("[cylwindrot]: Only (R,phi) can be used in 2D!\n");
  }

  /* Allocate memory for solution */
  if ((RootSoln = (ConsS***)calloc_3d_array(nx3,nx2,nx1,sizeof(ConsS))) == NULL)
    ath_error("[cylwindrot]: Error allocating memory for solution\n");

  ang_mom = par_getd("problem","ang_mom");
  c_infty = par_getd("problem","c_infty");
  vz0     = par_getd("problem","vz0");
  iprob   = par_geti("problem","iprob");
  printf("gamma = %f,\t ang_mom = %f,\t c_infty = %f\n", Gamma, ang_mom, c_infty);

  beta = 2.0*Gamma_1/(Gamma+1.0);
  xs = (3.0-Gamma+sqrt(SQR(Gamma-3.0)-16.0*SQR(ang_mom)))/4.0;
  lambda_s = 1.0/Gamma_1*pow(xs,beta)+pow(xs,beta-1.0)-0.5*SQR(ang_mom)*pow(xs,beta-2.0);
  lambda_s = pow(lambda_s/(0.5+1.0/Gamma_1),1.0/beta);
  vs = c_infty*pow(lambda_s/xs,0.5*beta);
  printf("xs = %13.10f,\t lambda_s = %13.10f,\t vs = %13.10f\n", xs, lambda_s, vs);

  // Compute 1D wind/accretion solution
  for (i=il; i<=iu; i++) {
    cc_pos(pG,i,j,k,&x1,&x2,&x3);
    memset(&(pG->U[ks][js][i]),0.0,sizeof(ConsS));
    vs = pow(lambda_s/x1,0.5*beta);

    switch(iprob) {
      case 1: /* Wind */
              if (x1 < xs) {
                a = TINY_NUMBER;  b = vs;
              }
              else {
                a = vs;           b = HUGE_NUMBER;
              }
              break;
      case 2: /* Accretion */
              if (x1 < xs) {
                a = vs;           b = HUGE_NUMBER;
              }
              else {
                a = TINY_NUMBER;  b = vs;
              }
              break;
      default:  ath_error("[cylwindrot]:  Not an accepted problem number!\n");
    }

    converged = bisection(myfunc,a,b,x1,&v);
    if (!converged) ath_error("[cylwindrot]:  Bisection did not converge!\n");

    pG->U[ks][js][i].d   = lambda_s/(x1*v);
    pG->U[ks][js][i].M1  = lambda_s/x1;
    if (iprob==2)
      pG->U[ks][js][i].M1  *= -1.0;
    pG->U[ks][js][i].M2  = pG->U[ks][js][i].d*ang_mom/x1;
    pG->U[ks][js][i].M3  = pG->U[ks][js][i].d*vz0;

        /* Initialize total energy */
#ifndef ISOTHERMAL
        pgas0 = 1.0/Gamma;
        pgas = pgas0*pow(pG->U[ks][js][i].d,Gamma);
        pG->U[ks][js][i].E = pgas/Gamma_1
          + 0.5*(SQR(pG->U[ks][js][i].M1) + SQR(pG->U[ks][js][i].M2) + SQR(pG->U[ks][js][i].M3))/pG->U[ks][js][i].d;
#endif /* ISOTHERMAL */
  }

  /* Copy 1D solution and save */
  for (k=kl; k<=ku; k++) {
    for (j=jl; j<=ju; j++) {
      for (i=il; i<=iu; i++) {
        pG->U[k][j][i] = pG->U[ks][js][i];
        RootSoln[k][j][i] = pG->U[ks][js][i];
      }
    }
  }

  StaticGravPot = grav_pot;
  bvals_mhd_fun(pDomain,left_x1,do_nothing_bc);
  bvals_mhd_fun(pDomain,right_x1,do_nothing_bc);

  return;
}
Ejemplo n.º 26
0
int main() {
	FILE *fp = fopen("BigShips_1280x720_60Hz_i420_part1_result.csv","w");
	double sheet1[600][3];	//用于存储600条QP、Bits、Y PSNR数据
	double sheet2[600][3];
	double sheet3[600][3];
	double sheet4[600][3];

	double QP[8];
	double R[8];
	double D[8];
	double lambda[8];
	double alpha[4];
	double beta[4];
	double c[4];
	double k[4];

	double Rbudget = 2000.0;	//2000kb/s
	double u;				//u=1/μ
	double low = -10000.0;		//二分法求公式(10)的解,区间下限
	double high = 20000.0;		//二分法求公式(10)的解,区间上限
	int framerate = 60;
	int imageWidth = 1280;
	int imageHeight = 720;

	parseCSV("BigShips_1280x720_60Hz_i420_part1.csv", sheet1, framerate, imageWidth, imageHeight);	//解析CSV文件,将600行R、D、QP存入sheet数组
	parseCSV("BigShips_1280x720_60Hz_i420_part2.csv", sheet2, framerate, imageWidth, imageHeight);
	parseCSV("City_corr_1280x720_60Hz_i420_part1.csv", sheet3, framerate, imageWidth, imageHeight);
	parseCSV("City_corr_1280x720_60Hz_i420_part2.csv", sheet4, framerate, imageWidth, imageHeight);

	for (int i = 0; i < 600; i ++) {
		for (int j = 0; j < 2; j++) {
			QP[j] = sheet1[i + j][0];
			R[j] = sheet1[i + j][1];
			D[j] = sheet1[i + j][2];

			QP[j+2] = sheet2[i + j][0];
			R[j+2] = sheet2[i + j][1];
			D[j+2] = sheet2[i + j][2];

			QP[j+4] = sheet3[i + j][0];
			R[j+4] = sheet3[i + j][1];
			D[j+4] = sheet3[i + j][2];

			QP[j+6] = sheet4[i + j][0];
			R[j+6] = sheet4[i + j][1];
			D[j+6] = sheet4[i + j][2];
		}
		for (int j = 0; j < 4; j++) {
			lambda[j * 2] = exp((QP[j * 2] - 13.7122) / 4.2005);			//用两个QP(对应两个Lamda), 编码出两个R,对应两个D(R)
			lambda[j * 2 + 1] = exp((QP[j * 2 + 1] - 13.7122) / 4.2005);	

			beta[j] = log(R[j * 2] / R[j * 2 + 1]) / log(lambda[j * 2] / lambda[j * 2 + 1]);	//把 α 和 β 求解出来
			alpha[j] = R[j * 2] / pow(lambda[j * 2], beta[j]);

			k[j] = -log(D[j * 2] / D[j * 2 + 1]) / log(R[j * 2] / R[j * 2 + 1]);	//把c k 求解出来
			c[j] = D[j * 2] / pow(R[j * 2], -k[j]);
		}

		u = bisection(Rbudget, high, low, c, k);	//二分法求公式10的解

		fprintf(fp, "R,lambda,QP\n");	//即将保存的数据的表头:R	lambda	QP

		for (int j = 0; j < 4; j++) {
			R[j] = pow(k[j] * c[j] * u, 1 / (k[j] + 1));			//利用Mu把各对c_i k_i 的 R_i算出来
			lambda[j] = pow(R[j] / alpha[j], 1 / beta[j]);			//利用R_i, 重新求解出λ_i
			QP[j] = 4.2005*log(lambda[j]) + 13.7122;				//利用λ_i重新求解出QP_i
			fprintf(fp, "%lf,%lf,%lf\n", R[j], lambda[j], QP[j]);	//保存数据
		}
	}

	return 0;
}
Ejemplo n.º 27
0
void surftempskin() {
    int tskiniter;
    int tskinitermax;
/*    float tkel = 273.16;   */  /*0 point of water in K*/
    double dtsurf,dtsurf1;
    double tsurf,tsurfold,tsurfold1;

    turbfluxes();

/*    printf("A %f %f  ",jd2,surftemp[i][j]);*/
    tsurf = surftemp[i][j];		/* in deg C*/
    tsurf1 = surftemp[i][j] - tinterv;
    tsurf2 = surftemp[i][j] + tinterv;
    dtsurf = 2.*taccur;
    dtsurf1 = 2.*taccur;
    tsurfold = tsurf1;

    tskiniter = 0;
    tskinitermax = 40;

    while ((dtsurf > taccur) && (dtsurf1 > 0.)) {
        tskiniter = tskiniter+1;
        
        tsurfold1 = tsurfold;
        tsurfold = tsurf;

        bisection();
        tsurf = tbisection;

        if (tsurf >= 0.)
            tsurf = 0.;
        tspechum = tsurf;
        kspechum = 2;
        spechum();

		surftemp[i][j] = tsurf;
        turbfluxes();

//        tsurfenergybalance(tsurf);
        if (tsurf >= 0.)
            tsurfenergybalance(0.);
        sourceskin = balancetsurf;
        if (sourceskin < 0.)
            sourceskin = 0.;

        dtsurf = fabs(tsurf - tsurfold);
        dtsurf1 = fabs(tsurf - tsurfold1);
        
        if ( tskiniter >= tskinitermax) { /* no solution found */
        fprintf(outcontrol," function surftempskin: more than %d iterations necessary %f %f %f %f %f \n",
                tskinitermax,taccur,dtsurf,tsurf,tsurfold,sourceskin);
        tsurf = 0.5 * (tsurf + tsurfold);
        dtsurf = 0.;
        }
        
    }

    if ((dtsurf > taccur) && (dtsurf1 == 0.) && (tskiniter > tskinitermax)) { /* no solution found */
      fprintf(outcontrol," function surftempskin: nosolution found, varies between: %d %f %f %f %f \n",
                tskiniter,taccur,dtsurf,tsurf,tsurfold);
      tsurf = 0.5 * (tsurf + tsurfold);
    }

    surftemp[i][j] = tsurf;

    return;
}
Ejemplo n.º 28
0
PolygonalMesh* Polygonizer::computeSurfaceNetSIG02(float epsilon, float tau)
{
	float p[3];
	bool ***isIn = new bool**[dimZ+1];
	bool ***isValid = new bool**[dimZ+1];
	for(int i=0; i<dimZ+1; i++){
		isIn[i] = new bool*[dimY+1];
		isValid[i] = new bool*[dimY+1];
		p[2] = originZ + i*spaceZ;
		for(int j=0; j<dimY+1; j++){
			isIn[i][j] = new bool[dimX+1];
			isValid[i][j] = new bool[dimX+1];
			p[1] = originY + j*spaceY;
			for(int k=0; k<dimX+1; k++){
				p[0] = originX + k*spaceX;
				isIn[i][j][k] 
					= (func->value(p[0], p[1], p[2], isValid[i][j][k]) > 0);
			}
		}
	}

	int ***index = new int**[dimZ+1];
	for(int i=0; i<dimZ+1; i++){
		index[i] = new int*[dimY+1];
		for(int j=0; j<dimY+1; j++){
			index[i][j] = new int[dimX+1];
			for(int k=0; k<dimX+1; k++)
				index[i][j][k] = -1;
		}
	}

	int current = 0;
	int face_N = 0;
	for(int i=0; i<dimZ; i++)
		for(int j=0; j<dimY; j++)
			for(int k=0; k<dimX-1; k++){
				if(!isValid[i][j][k] || !isValid[i][j][k+1])
					continue;
				if((!isIn[i][j][k] && isIn[i][j][k+1]) || 
				    (isIn[i][j][k] && !isIn[i][j][k+1])){
					face_N++;
					if(index[i][j][k+1] < 0){
						index[i][j][k+1] = current;
						current++;
					}
					if(index[i][j+1][k+1] < 0){
						index[i][j+1][k+1] = current;
						current++;
					}
					if(index[i+1][j][k+1] < 0){
						index[i+1][j][k+1] = current;
						current++;
					}
					if(index[i+1][j+1][k+1] < 0){
						index[i+1][j+1][k+1] = current;
						current++;
					}
				}
			}

	for(int i=0; i<dimX; i++)
		for(int j=0; j<dimZ; j++)
			for(int k=0; k<dimY-1; k++){
				if(!isValid[j][k][i] || !isValid[j][k+1][i])
					continue;
				if((!isIn[j][k][i] && isIn[j][k+1][i]) || 
				    (isIn[j][k][i] && !isIn[j][k+1][i])){
					face_N++;
					if(index[j][k+1][i] < 0){
						index[j][k+1][i] = current;
						current++;
					}
					if(index[j+1][k+1][i] < 0){
						index[j+1][k+1][i] = current;
						current++;
					}
					if(index[j][k+1][i+1] < 0){
						index[j][k+1][i+1] = current;
						current++;
					}
					if(index[j+1][k+1][i+1] < 0){
						index[j+1][k+1][i+1] = current;
						current++;
					}
				}
			}

	for(int i=0; i<dimY; i++)
		for(int j=0; j<dimX; j++)
			for(int k=0; k<dimZ-1; k++){
				if(!isValid[k][i][j] || !isValid[k+1][i][j])
					continue;
				if((!isIn[k][i][j] && isIn[k+1][i][j]) || 
				    (isIn[k][i][j] && !isIn[k+1][i][j])){
					face_N++;
					if(index[k+1][i][j] < 0){
						index[k+1][i][j] = current;
						current++;
					}
					if(index[k+1][i+1][j] < 0){
						index[k+1][i+1][j] = current;
						current++;
					}
					if(index[k+1][i][j+1] < 0){
						index[k+1][i][j+1] = current;
						current++;
					}
					if(index[k+1][i+1][j+1] < 0){
						index[k+1][i+1][j+1] = current;
						current++;
					}
				}
			}
	
	PolygonalMesh* mesh = new PolygonalMesh;
	int vertex_N = current;
	mesh->setVertexCount(vertex_N);
	float (*vertex)[3] = mesh->vertex;
	int* degree = mesh->degree_f = new int[vertex_N];
	current = 0;
	for(int i=0; i<vertex_N; i++){
		vertex[i][0] = vertex[i][1] = vertex[i][2] = 0;
		degree[i] = 0;
	}
	/*
	for(i=0; i<dimZ+1; i++)
		for(int j=0; j<dimY+1; j++)
			for(int k=0; k<dimX+1; k++)
				if(index[i][j][k] >= 0){
					index[i][j][k] = current;
					vertex[current][0] = spaceX*((float)k-0.5f) + originX;
					vertex[current][1] = spaceY*((float)j-0.5f) + originY;
					vertex[current][2] = spaceZ*((float)i-0.5f) + originZ;
					current++;
				}
				*/


	mesh->setFaceCount(face_N);
	double (*Q)[10] = new double[vertex_N][10];
	for(int i=0; i<vertex_N; i++)
		MAT_INIT(Q[i]);
	for(int i=0; i<face_N; i++)
		mesh->setPolygonCount(i, 4);
	face_N = 0;
	int **face = mesh->face;
	bool flag = false;
	for(int i=0; i<dimZ; i++)
		for(int j=0; j<dimY; j++)
			for(int k=0; k<dimX-1; k++){
				if(!isValid[i][j][k] || !isValid[i][j][k+1])
					continue;
				if(isIn[i][j][k] && !isIn[i][j][k+1]){
					face[face_N][0] = index[i][j][k+1];
					face[face_N][1] = index[i][j+1][k+1];
					face[face_N][2] = index[i+1][j+1][k+1];
					face[face_N][3] = index[i+1][j][k+1];
					face_N++;
					flag = true;
				}
				else if(!isIn[i][j][k] && isIn[i][j][k+1]){
					face[face_N][0] = index[i][j][k+1];
					face[face_N][1] = index[i+1][j][k+1];
					face[face_N][2] = index[i+1][j+1][k+1];
					face[face_N][3] = index[i][j+1][k+1];
					face_N++;
					flag = true;
				}
				if(!flag)
					continue;
				flag = false;
				float p[3], s[3], e[3];
				s[0] = originX + k*spaceX;
				e[0] = originX + (k+1)*spaceX;
				s[1] = e[1] = originY + j*spaceY;
				s[2] = e[2] = originZ + i*spaceZ;
				bisection(p, s, e, epsilon);
				
				float g[3];
				func->gradient(g, p[0], p[1], p[2]);
				double len = PolygonalMesh::LENGTH(g);
				//if((float)len == 0)
					//continue;
				double nor[3];
				nor[0] = g[0]/len;
				nor[1] = g[1]/len;
				nor[2] = g[2]/len;

				double d = -PolygonalMesh::DOT(nor, p);
				double Q_tmp[10];
				MATRIX(Q_tmp, nor, d);

				int i0 = index[i][j][k+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[i][j+1][k+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[i+1][j+1][k+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[i+1][j][k+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;
			}

	for(int i=0; i<dimX; i++)
		for(int j=0; j<dimZ; j++)
			for(int k=0; k<dimY-1; k++){
				if(!isValid[j][k][i] || !isValid[j][k+1][i])
					continue;
				if(isIn[j][k][i] && !isIn[j][k+1][i]){
					face[face_N][0] = index[j][k+1][i];
					face[face_N][1] = index[j+1][k+1][i];
					face[face_N][2] = index[j+1][k+1][i+1];
					face[face_N][3] = index[j][k+1][i+1];
					face_N++;
					flag = true;
				}
				else if(!isIn[j][k][i] && isIn[j][k+1][i]){
					face[face_N][0] = index[j][k+1][i];
					face[face_N][1] = index[j][k+1][i+1];
					face[face_N][2] = index[j+1][k+1][i+1];
					face[face_N][3] = index[j+1][k+1][i];
					face_N++;
					flag = true;
				}
				if(!flag)
					continue;
				flag = false;
				float p[3], s[3], e[3];
				s[1] = originY + k*spaceY;
				e[1] = originY + (k+1)*spaceY;
				s[2] = e[2] = originZ + j*spaceZ;
				s[0] = e[0] = originX + i*spaceX;
				bisection(p, s, e, epsilon);
				
				float g[3];
				func->gradient(g, p[0], p[1], p[2]);
				double len = PolygonalMesh::LENGTH(g);
				//if((float)len == 0)
					//continue;
				double nor[3];
				nor[0] = g[0]/len;
				nor[1] = g[1]/len;
				nor[2] = g[2]/len;

				double d = -PolygonalMesh::DOT(nor, p);
				double Q_tmp[10];
				MATRIX(Q_tmp, nor, d);
				
				int i0 = index[j][k+1][i];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[j+1][k+1][i];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[j+1][k+1][i+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[j][k+1][i+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;
			}

	for(int i=0; i<dimY; i++)
		for(int j=0; j<dimX; j++)
			for(int k=0; k<dimZ-1; k++){
				if(!isValid[k][i][j] || !isValid[k+1][i][j])
					continue;
				if(isIn[k][i][j] && !isIn[k+1][i][j]){
					face[face_N][0] = index[k+1][i][j];
					face[face_N][1] = index[k+1][i][j+1];
					face[face_N][2] = index[k+1][i+1][j+1];
					face[face_N][3] = index[k+1][i+1][j];
					face_N++;
					flag = true;
				}
				else if(!isIn[k][i][j] && isIn[k+1][i][j]){
					face[face_N][0] = index[k+1][i][j];
					face[face_N][1] = index[k+1][i+1][j];
					face[face_N][2] = index[k+1][i+1][j+1];
					face[face_N][3] = index[k+1][i][j+1];
					face_N++;
					flag = true;
				}
				if(!flag)
					continue;
				flag = false;
				float p[3], s[3], e[3];
				s[2] = originZ + k*spaceZ;
				e[2] = originZ + (k+1)*spaceZ;
				s[0] = e[0] = originX + j*spaceX;
				s[1] = e[1] = originY + i*spaceY;
				bisection(p, s, e, epsilon);
				
				float g[3];
				func->gradient(g, p[0], p[1], p[2]);
				double len = PolygonalMesh::LENGTH(g);
				//if((float)len == 0)
					//continue;
				double nor[3];
				nor[0] = g[0]/len;
				nor[1] = g[1]/len;
				nor[2] = g[2]/len;

				double d = -PolygonalMesh::DOT(nor, p);
				double Q_tmp[10];
				MATRIX(Q_tmp, nor, d);

				int i0 = index[k+1][i][j];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[k+1][i][j+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[k+1][i+1][j+1];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;

				i0 = index[k+1][i+1][j];
				MAT_SUM(Q[i0], Q_tmp);
				vertex[i0][0] += p[0];
				vertex[i0][1] += p[1];
				vertex[i0][2] += p[2];
				degree[i0]++;
			}
	
	//FOR SVD
			
	vnl_matrix< float > A( 3, 3, 0. ); 
	vnl_vector< float > b(3, 0.), x(3, 0.);

	for(int i=0; i<vertex_N; i++){
		if(degree[i] == 0)
			continue;
		vertex[i][0] /= degree[i];
		vertex[i][1] /= degree[i];
		vertex[i][2] /= degree[i];
continue;
		A[0][0] = (float)Q[i][0];
		A[1][0] = A[0][1] = (float)Q[i][1];
		A[2][0] = A[0][2] = (float)Q[i][2];
		A[1][1] = (float)Q[i][3];
		A[1][2] = A[2][1] = (float)Q[i][4];
		A[2][2] = (float)Q[i][5];

		float Av[3];
		MAT_BY_VEC(Av, Q[i], vertex[i]);
		b[0] = -(float)Q[i][6] - Av[0];
		b[1] = -(float)Q[i][7] - Av[1];
		b[2] = -(float)Q[i][8] - Av[2];

    vnl_svd<float> svd( A );
    svd.zero_out_absolute( 0.0000001 );

    x = svd.solve( b );

    if(fabs(x[1]) > spaceX || fabs(x[2]) > spaceY || fabs(x[3]) > spaceZ)
			continue;

		mesh->vertex[i][0] += x[1];
		mesh->vertex[i][1] += x[2];
		mesh->vertex[i][2] += x[3];
	}

	for(int i=0; i<dimZ+1; i++){
		for(int j=0; j<dimY+1; j++){
			delete[] isIn[i][j];
			delete[] index[i][j];
		}
		delete[] isIn[i];
		delete[] index[i];
	}
	delete[] isIn;
	delete[] index;
	delete[] Q;
	delete[] isValid;

	return mesh;
}
Ejemplo n.º 29
0
int main(int argc, char* argv[])
{
	int input[] = { 5, -1, 4, 12 };
	int input_size = 4;

	int input_sorted[] = { -4, 1, 22, 66, 89, 120, 238 };
	int input_sorted_size = 7;

	// 2. function pointers
	// direct invocation
	printf("Max is %d\n", max(input, input_size));
	// function pointer invocation
	int(*sortfunc)(int elements[], int size) = max;
	printf("Max (function pointer) %d\n", sortfunc(input, input_size));

	// 3. recursivity
	printf("recursive fibonacci(12) = %d\n", fibonacci_recursive(12));
	printf("iterative fibonacci(12) = %d\n", fibonacci_iterative(12));

	// 4. search
	// 4a. simple search 
	harness_search(input, input_size, 4, "search", search);
	harness_search(input, input_size, 2, "search", search);
	// 4b. binary search
	harness_search(input_sorted, input_sorted_size, 89, "search_binary", search_binary);
	harness_search(input_sorted, input_sorted_size, 500, "search_binary", search_binary);
	harness_search(input_sorted, input_sorted_size, -40, "search_binary", search_binary);
	harness_search(input_sorted, input_sorted_size, 140, "search_binary", search_binary);

	// 4. merge
	int to_sort[] = { 9, -1, 3, 11, 4, 99, 11, 0 };
	int to_sort_size = 8;

	printf("Performing merge sort\n");
	printf("- unsorted: ");
	print_array(to_sort, to_sort_size);
	sort_merge(to_sort, to_sort_size);
	printf("- sorted: ");
	print_array(to_sort, to_sort_size);

	// 5. file access
	int matrix[4][4] = {
		{ 1, 2, 3, 4 },
		{ 5, 6, 7, 8 },
		{ -1, -2, -3, -4 },
		{ 9, 78, 12, -1 }
	};
	write_matrix_to_file(matrix, "matrix.txt");
	int matrix_out[4][4];
	read_matrix_from_file(matrix_out, "matrix.txt");
	printf("Matrix read from file:\n");
	print_matrix(matrix_out);

	// 6/7. binary file access
	// delete 'db' before using
	unlink("students.dat");
	STUDENT student1;
	student1.an_studiu = 1;
	student1.grupa = 1014;
	student1.nume = "Salut";

	STUDENT student2;
	student2.an_studiu = 2;
	student2.grupa = 1084;
	student2.nume = "Pa";
	
	student_append(student1, "students.dat");
	student_append(student2, "students.dat");

	student_print_all("students.dat");

	// XX. bisection method
	// f(x) = x^3 - x - 2
	// f(1) = -2
	// f(2) = -4
	int res = bisection(1, 2, equation);
	printf("Bisected x to be %d\n", res);

	printf("GCD: %d\n", gcd(299792458, 6447287));

	return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
//Do intial guesses need to be found 
int main(int argc, char **argv){
    printf("Root 1 %.4f \n",bisection(poly_function,0,1));
    printf("Root 2 %.4f\n", bisection(poly_function,-3,-2));
    printf("Root 3 %.4f\n", bisection(poly_function,1,2));
    return 0;
}