예제 #1
0
Rational::Rational (double x)
{
    int sign;

    if (x >= 0)
    {
	sign = 1;	// positive
    }
    else if (x < 0)
    {
	sign = -1;	// negative
	x = -x;
    }
    else
    {
	n = 0;		// NaN
	d = 0;
	return;
    }

    if (x >= (1U << 31) - 0.5)
    {
	n = sign;	// infinity
	d = 0;
	return;
    }

    double e = (x < 1? 1: x) / (1U << 30);
    d = (unsigned int) denom (x, e);
    n = sign * (int) floor (x * d + 0.5);
}
예제 #2
0
파일: qff.cpp 프로젝트: johnkerl/spffl
// ----------------------------------------------------------------
intmod_t intmod_from_rat(intrat_t r, int p)
{
	intmod_t numer(r.get_numerator(),   p);
	intmod_t denom(r.get_denominator(), p);

	return numer / denom;
}
예제 #3
0
void fincr(_MIPD_ flash x,int n,int d,flash y)
{ /* increment x by small fraction n/d - y=x+(n/d) */
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return;

    MR_IN(43)

    if (d<0)
    {
        d=(-d);
        n=(-n);
    }
    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    mr_mip->check=OFF;
    premult(_MIPP_ mr_mip->w1,d,mr_mip->w5);
    premult(_MIPP_ mr_mip->w2,d,mr_mip->w6);
    premult(_MIPP_ mr_mip->w2,n,mr_mip->w0);
    add(_MIPP_ mr_mip->w5,mr_mip->w0,mr_mip->w5);
    mr_mip->check=ON;
    if (d==1 && fit(mr_mip->w5,mr_mip->w6,mr_mip->nib))
        fpack(_MIPP_ mr_mip->w5,mr_mip->w6,y);
    else
        mround(_MIPP_ mr_mip->w5,mr_mip->w6,y);
    MR_OUT
}
예제 #4
0
파일: Test.cpp 프로젝트: Rosefield/BigNum
void testDivRand512Bit() {
    std::chrono::time_point<std::chrono::system_clock> start, end;
    std::chrono::duration<double> elapsed_time;
    //512 bits
    BigInt num("22479199231365811817124860008034"
               "86229160630675450396401816569207"
               "37104752501976414843519588079979"
               "01710354041585586289392397420347"
               "216513925045972181584884921");
    //500 bits
    BigInt denom("351508594074011603394279375147"
                 "626833956407011572250308540816"
                 "854541429976970595757637034702"
                 "593071101429245293222692961211"
                 "2896690197169368617519259819528");
    start = std::chrono::system_clock::now();
    end = std::chrono::system_clock::now();
    BigInt result = num / denom;
    elapsed_time = end - start;
#ifdef _PRINT_VALS
    std::cout<< "DivRand512Bit took: " << elapsed_time.count() << " computing " << result << std::endl;
#endif
    std::vector<limb_t> actual{6395};
    std::cout << "512b num / 500b num Correct? " << testEquals(result, actual) << std::endl;   
}
예제 #5
0
mpf_class MpfFromRational(Signal &sig, const Rational &ratio)
{
	if (ratio.denom == 0) {
		Operator::SetError_DivideByZero(sig);
		return mpf_class(0);
	}
	mpq_class numer(ratio.numer);
	mpq_class denom(ratio.denom);
	return numer / denom;
}
예제 #6
0
Number Parser::createNumber(string number, char first){
    Number result;
    //This is probably lazy/ bad, but it basically makes sure that theres no junk before the actual operation.
    if (first != 's' && number.find("rt:") > 0){
        string base (number.find(':')+1, -1);
        string radicand (0, number.find('r')-1);
        result = Radical(createNumber(base, base.front()), createNumber(radicand, radicand.front()));
    }
    else if (first=='p' && number.at(1) =='i' && number.length() == 2){
        //create pi
        result = Constant("pi");
    }
    else if (first=='e' && number.length() == 1){
        //create e
        result = Constant("e");
    }
    else if (first == 's' && number.find("sqrt:") > 0){
        //create a square root
        string base (number.find(':')+1, -1);
        result = Radical(createNumber(base, base.front()), Integer(2));
    }
    else if (first == 'l' && number.find("log_") > 0){
        //create a log
        string base (number.find('_')+1, number.find(':'));
        string arg (number.find(':')+1, -1);
        result = Log(createNumber(base, base.front()), createNumber(arg, arg.front()));
    }
    //all numbers are created here
    else if (isdigit(first) && number.find_last_not_of("0123456789./") != -1){
        //find a '/' to create a fraction
        if(number.find_first_of('/') > 0){
            //check to make sure there is only one '/' in the fraction
            if (number.find_first_of('/') != number.find_last_of('/')) {
                //temporary error handling
                throw "Only one / per fracton";
            }
            //create a rational
            string numerator (0, number.find('/')-1);
            string denom ( number.find('/') + 1, -1);
            result = Rational(createNumber(numerator, numerator.front()), createNumber(denom, denom.front()));
        }
        if(number.find_first_of('.') > 0){
            if (number.find_first_of('.') != number.find_last_of('.')){
                throw "Only one . per decimal";
            }
            //create a rational from a decimal
            
            result = Rational(number));
        }
        //finally, create an integer
        result = Integer(stoi(number));
    }

    return result;
}
예제 #7
0
int fcomp(_MIPD_ flash x,flash y)
{ /* compares two Flash numbers             *
   * returns -1 if y>x; +1 if x>y; 0 if x=y */
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return 0;

    MR_IN(39)
    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ y,mr_mip->w2);
    mr_mip->check=OFF;
    multiply(_MIPP_ mr_mip->w1,mr_mip->w2,mr_mip->w5);
    numer(_MIPP_ y,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    multiply(_MIPP_ mr_mip->w1,mr_mip->w2,mr_mip->w0);
    mr_mip->check=ON;
    MR_OUT
    return (mr_compare(mr_mip->w5,mr_mip->w0));
}
예제 #8
0
파일: weights.c 프로젝트: afc523/comet
int exact_test_helper(double *pval, int *num_tbls, int k, double pvalthresh, int num_entries,
                      int N, double numerator, int *margins, int *ex_cells, int *co_cells,
                      int num_co_cells, int *tbl, int **mar_stack, int co_in, int T_rem, int T_obs){
  int res = UNDER_THRESH;
  if (co_in >= num_co_cells){
    derive_remaining_cells( k, N, margins, ex_cells, tbl, mar_stack[co_in] );
    if (contains_negative(tbl, num_entries) == 0){
      double addp = exp( numerator - denom( k, num_entries, N,  tbl) );
      pval[0] += addp;
      if (T_obs < sum_cells(tbl, ex_cells, k)){ // T > T_x
        pval[1] += addp;
      }
      num_tbls[0] += 1;
    }
  if ((pval[0]+pval[1])/2 > pvalthresh) {	
      res = OVER_THRESH;
    }
  }
  else {
    // Define required variables
    int i, cell, val, MarRem;
    double coef;
    int *mar_rems;
    
    cell     = co_cells[co_in];
    coef     = num_ones( cell );
    mar_rems = mar_stack[co_in];
    
    // Determine which variables are in the margin
    MarRem = min_affected_margin( k, cell, mar_rems );
    
    // Iterate over the possible values the current cell can take
    for (val = 0; val < min(MarRem, (int) floor(T_rem/coef)) + 1; val++){
      // Update margins
      for (i=0; i < k; i++){
        if (cell & (1 << i)) mar_stack[co_in+1][i] = mar_rems[i] - val;
        else mar_stack[co_in+1][i] = mar_rems[i];
      }
      
      // Create new table using the current value
      tbl[cell] = val;
      res = exact_test_helper( pval, num_tbls, k, pvalthresh, num_entries, N, numerator,
                               margins, ex_cells, co_cells, num_co_cells, tbl,
                               mar_stack, co_in + 1, T_rem-coef*val, T_obs);
      if (res < 0) {
        break;
      }
    }
  }
  return res;
}
예제 #9
0
  void Bead_ParticleSet::getDrift(vector<RealType>& LogNorm) {
    int nPsi(Properties.rows());
      //compute Drift
    RealType denom(0.e0),wgtpsi;
    Drift=0.e0;
    for(int ipsi=0; ipsi<nPsi; ipsi++) {
      wgtpsi=BeadSignWgt[ipsi]*std::exp(2.0*( Properties(ipsi,LOGPSI)- LogNorm[ipsi]
					      -Properties(0,LOGPSI)   + LogNorm[0]));
      denom += wgtpsi;
      Drift += (wgtpsi*(*DriftVectors[ipsi]));
    }
    denom=1.0/denom;
    Drift *= denom;
  }
예제 #10
0
void frecip(_MIPD_ flash x,flash y)
{ /* set y=1/x */
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return;

    MR_IN(41)

    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    fpack(_MIPP_ mr_mip->w2,mr_mip->w1,y);

    MR_OUT
}
예제 #11
0
파일: Test.cpp 프로젝트: Rosefield/BigNum
void testDivAddBack() {
    std::chrono::time_point<std::chrono::system_clock> start, end;
    std::chrono::duration<double> elapsed_time;
    BigInt num("12345678998765432112345678901111111111222222222");
    BigInt denom("12345678998765431212340871");
    start = std::chrono::system_clock::now();
    BigInt q = num / denom;
    end = std::chrono::system_clock::now();
    elapsed_time = end - start;
#ifdef _PRINT_VALS
    std::cout<< "testDivAddBack took: " << elapsed_time.count() << " computing " << q << std::endl;
#endif 
   std::vector<limb_t> actual{216,1804819339,1587616964};
    std::cout << "Division\'s 'add back' case Correct? " << testEquals(q, actual) << std::endl;   
}
예제 #12
0
Line planePlaneIntersection(const Plane& p1,const Plane& p2)
{
    //Process: http://stackoverflow.com/a/17628505
    Vector normal1=Vector(p1.getA(),p1.getB(),p1.getC()); //vector normal to p1
    Vector normal2=Vector(p2.getA(),p2.getB(),p2.getC()); //vector normal to p2
    Vector cross=Vector::cross(normal1, normal2); //vector parallel to line of intersection
    
    if (fabs(cross.norm())<EPS)
    { //planes are parallel
        Point zero=Point(0,0,0);
        return Line(zero,zero);
    }
    double a1=p1.getA();
    double b1=p1.getB();
    double c1=p1.getC();
    double d1=-1*p1.getD();
    double a2=p2.getA();
    double b2=p2.getB();
    double c2=p2.getC();
    double d2=-1*p2.getD();
    double a3=cross.getX();
    double b3=cross.getY();
    double c3=cross.getZ();
    double d3=0;
    
    //solve with cramers rule
    Matrix3x3 denom(a1,b1,c1,
                    a2,b2,c2,
                    a3,b3,c3);
    Matrix3x3 xNum(d1,b1,c1,
                   d2,b2,c2,
                   d3,b3,c3);
    Matrix3x3 yNum(a1,d1,c1,
                   a2,d2,c2,
                   a3,d3,c3);
    Matrix3x3 zNum(a1,b1,d1,
                   a2,b2,d2,
                   a3,b3,d3);
    double denomDeterminant=denom.determinant();
    
    double xsolution=xNum.determinant()/denomDeterminant;
    double ysolution=yNum.determinant()/denomDeterminant;
    double zsolution=zNum.determinant()/denomDeterminant;
    
    Point onLine(xsolution,ysolution,zsolution);
    Point onLine2=onLine+cross;
    return Line(onLine,onLine2);
}
예제 #13
0
void ftrunc(_MIPD_ flash x,big y,flash z)
{ /* sets y=int(x), z=rem(x) - returns *
   * y only for ftrunc(x,y,y)       */
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return;

    MR_IN(45)
    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    divide(_MIPP_ mr_mip->w1,mr_mip->w2,mr_mip->w3);
    copy(mr_mip->w3,y);
    if (y!=z) fpack(_MIPP_ mr_mip->w1,mr_mip->w2,z);
    MR_OUT
}
예제 #14
0
void fpmul(_MIPD_ flash x,int n,int d,flash y)
{ /* multiply x by small fraction n/d - y=x*n/d */
    int r,g;
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return;
    if (n==0 || size(x)==0)
    {
        zero(y);
        return;
    }
    if (n==d)
    {
        copy(x,y);
        return;
    }

    MR_IN(42)

    if (d<0)
    {
        d=(-d);
        n=(-n);
    }
    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    r=subdiv(_MIPP_ mr_mip->w1,d,mr_mip->w3);
    g=igcd(d,r);
    r=subdiv(_MIPP_ mr_mip->w2,n,mr_mip->w3);
    g*=igcd(n,r);
    mr_mip->check=OFF;
    premult(_MIPP_ mr_mip->w1,n,mr_mip->w5);
    premult(_MIPP_ mr_mip->w2,d,mr_mip->w6);
    subdiv(_MIPP_ mr_mip->w5,g,mr_mip->w5);
    subdiv(_MIPP_ mr_mip->w6,g,mr_mip->w6);
    mr_mip->check=ON;
    if (fit(mr_mip->w5,mr_mip->w6,mr_mip->nib))
        fpack(_MIPP_ mr_mip->w5,mr_mip->w6,y);
    else
        mround(_MIPP_ mr_mip->w5,mr_mip->w6,y);
    MR_OUT
}
int Intersect(const TSegment2<NumericType> &S1, const TSegment2<NumericType> &S2, TPt2<NumericType> *x){
	typedef TVec2<NumericType> vec_t;
	vec_t v1(S1[1]-S1[0]), v2(S2[1]-S2[0]);
	vec_t v3(S2[0]-S1[0]);
	NumericType denom(vec_t::Cross(v1,v2));
	if(0 == denom){
		// parallel segments
		TLine2<NumericType> L1(S1.Line());
		if(L1.SideOf(S2[0]) == 0){
			// collinear segments, find endpoints of overlap
			NumericType t0(L1.Projection(S2[0]));
			NumericType t1(L1.Projection(S2[1]));
			if(t0 > t1){ std::swap(t0,t1); }
			// Returns midpoint of overlapping segment if possible
			if(NumericType(0) <= t0 && t0 <= NumericType(1)){
				if(NumericType(0) <= t1 && t1 <= NumericType(1)){
					if(NULL != x){
						x[0] = L1[(t0+t1)/NumericType(2)];
					}
				}else{
					if(NULL != x){
						x[0] = L1[(t0+NumericType(1))/NumericType(2)];
					}
				}
				return -1;
			}else if(NumericType(0) <= t1 && t1 <= NumericType(1)){
				if(NULL != x){
					x[0] = L1[t1/NumericType(2)];
				}
				return -1;
			}else{ // collinear but no intersections
				return 0;
			}
		}else{
			return 0;
		}
	}else{
		NumericType t(vec_t::Cross(v3,v2)/denom);
		if(NULL != x){ x[0] = S1.Line()[t]; }
		return 1;
	}
}
예제 #16
0
double fdsize(_MIPD_ flash w)
{ /* express flash number as double. */
    int i,s,en,ed;
    double n,d,b,BIGGEST;
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM || size(w)==0) return (0.0);

    MR_IN(11)

    BIGGEST=pow(2.0,(double)(1<<(MR_EBITS-4)));
    mr_mip->EXACT=FALSE;
    n=0.0;
    d=0.0;
    if (mr_mip->base==0) b=pow(2.0,(double)MIRACL);
    else b=(double)mr_mip->base;
    numer(_MIPP_ w,mr_mip->w1);
    s=exsign(mr_mip->w1);
    insign(PLUS,mr_mip->w1);
    en=(int)mr_mip->w1->len;
    for (i=0;i<en;i++)
        n=(double)mr_mip->w1->w[i]+(n/b);
    denom(_MIPP_ w,mr_mip->w1);
    ed=(int)mr_mip->w1->len;
    for (i=0;i<ed;i++)
        d=(double)mr_mip->w1->w[i]+(d/b);
    n/=d;
    while (en!=ed)
    {
        if (en>ed)
        {
            ed++;
            if (BIGGEST/b<n)
            {
                mr_berror(_MIPP_ MR_ERR_DOUBLE_FAIL);
                MR_OUT
                return (0.0);
            }
            n*=b;
        }
예제 #17
0
void CrossMapNormal<DEVICE_TYPE_CPU>(real* outputs,
                                     real* denoms,
                                     const real* inputs,
                                     size_t numSamples,
                                     size_t channels,
                                     size_t height,
                                     size_t width,
                                     size_t size,
                                     real scale,
                                     real pow) {
  size_t oneImage = height * width;
  size_t oneSample = channels * oneImage;

  CpuVector outputsV(numSamples * oneSample, outputs);
  CpuVector inputsV(numSamples * oneSample, const_cast<real*>(inputs));
  CpuVector denomsV(numSamples * oneSample, denoms);

  // f(x) = x * ( 1 + scale * SUM((x)^2) )^(-pow)
  // x represents inputs
  // f(x) represents outputs
  // denoms save the intermediate result for backward
  denomsV = denomsV.constant(1.0);
  const int start = -((int)size - 1) / 2;
  const int end = (int)size + start;
  for (size_t i = 0; i < numSamples; i++) {
    real* oneDenom = denoms + i * oneSample;
    real* oneInput = const_cast<real*>(inputs) + i * oneSample;
    for (int c = 0; c < (int)channels; c++) {
      CpuVector denom(oneImage, oneDenom + c * oneImage);
      for (int s = start; s < end; s++) {
        if (c + s >= 0 && c + s < (int)channels) {
          CpuVector input(oneImage, oneInput + (c + s) * oneImage);
          denom += input.square() * scale;
        }
      }
    }
  }

  outputsV = inputsV * denomsV.pow(-pow);
}
예제 #18
0
  void Bead_ParticleSet::getScaledDrift(vector<RealType>& LogNorm, RealType Tau) {
    int npsi(Properties.rows());
      //compute Drift
    RealType denom(0.e0),wgtpsi;
    Drift=0.e0;
    ParticlePos_t TMPgrad(Drift);
    for(int ipsi=0; ipsi<npsi; ipsi++) {
      wgtpsi=BeadSignWgt[ipsi]*std::exp(2.0*( Properties(ipsi,LOGPSI)- LogNorm[ipsi]
          -Properties(0,LOGPSI)   + LogNorm[0]));
      denom += wgtpsi;
      if (ScaleDrift){
        Tau_eff[ipsi] = setLargestScaledDriftPbyP(Tau,*Gradients[ipsi],TMPgrad);
//         RealType sc=getDriftScale(Tau,(*Gradients[ipsi]));
        (*DriftVectors[ipsi]) = TMPgrad;
        Drift += (wgtpsi*TMPgrad);
      } else {
        Tau_eff[ipsi]=Tau;
        (*DriftVectors[ipsi]) = Tau*(*Gradients[ipsi]);
        Drift += Tau*(wgtpsi*(*Gradients[ipsi]));
      }
    }
    denom=1.0/denom;
    Drift *= denom;
  }
예제 #19
0
// should output 187, 781
void test_denom() {
	printf("denom: %d, %d\n", denom(3.0 / 561.0), denom(-5571.0 / 781.0));
}
예제 #20
0
        void l0Smooth(InputArray src, OutputArray dst, double lambda, double kappa)
        {
            Mat S = src.getMat();

            CV_Assert(!S.empty());
            CV_Assert(S.depth() == CV_8U || S.depth() == CV_16U
            || S.depth() == CV_32F || S.depth() == CV_64F);

            dst.create(src.size(), src.type());

            if(S.data == dst.getMat().data){
                S = S.clone();
            }

            if(S.depth() == CV_8U)
            {
                S.convertTo(S, CV_32F, 1/255.0f);
            }
            else if(S.depth() == CV_16U)
            {
                S.convertTo(S, CV_32F, 1/65535.0f);
            }else if(S.depth() == CV_64F){
                S.convertTo(S, CV_32F);
            }

            const double betaMax = 100000;

            // gradient operators in frequency domain
            Mat otfFx, otfFy;
            float kernel[2] = {-1, 1};
            float kernel_inv[2] = {1,-1};
            psf2otf(Mat(1,2,CV_32FC1, kernel_inv), otfFx, S.rows, S.cols);
            psf2otf(Mat(2,1,CV_32FC1, kernel_inv), otfFy, S.rows, S.cols);

            vector<Mat> denomConst;
            Mat tmp = pow2absComplex(otfFx) + pow2absComplex(otfFy);

            for(int i = 0; i < S.channels(); i++){
                denomConst.push_back(tmp);
            }

            // input image in frequency domain
            vector<Mat> numerConst;
            dftMultiChannel(S, numerConst);
            /*********************************
            * solver
            *********************************/
            double beta = 2 * lambda;
            while(beta < betaMax){
                // h, v subproblem
                Mat h, v;

                filter2D(S, h, -1, Mat(1, 2, CV_32FC1, kernel), Point(0, 0),
                0, BORDER_REPLICATE);
                filter2D(S, v, -1, Mat(2, 1, CV_32FC1, kernel), Point(0, 0),
                0, BORDER_REPLICATE);

                Mat hvMag = h.mul(h) + v.mul(v);

                Mat mask;
                if(S.channels() == 1)
                {
                    threshold(hvMag, mask, lambda/beta, 1, THRESH_BINARY);
                }
                else if(S.channels() > 1)
                {
                    Mat *channels = new Mat[S.channels()];
                    split(hvMag, channels);
                    hvMag = channels[0];

                    for(int i = 1; i < S.channels(); i++){
                        hvMag = hvMag + channels[i];
                    }

                    threshold(hvMag, mask, lambda/beta, 1, THRESH_BINARY);

                    Mat in[] = {mask, mask, mask};
                    merge(in, 3, mask);

                    delete[] channels;
                }

                h = h.mul(mask);
                v = v.mul(mask);

                // S subproblem
                vector<Mat> denom(S.channels());
                for(int i = 0; i < S.channels(); i++){
                    denom[i] = beta * denomConst[i] + 1;
                }

                Mat hGrad, vGrad;
                filter2D(h, hGrad, -1, Mat(1, 2, CV_32FC1, kernel_inv));
                filter2D(v, vGrad, -1, Mat(2, 1, CV_32FC1, kernel_inv));

                vector<Mat> hvGradFreq;
                dftMultiChannel(hGrad+vGrad, hvGradFreq);

                vector<Mat> numer(S.channels());
                for(int i = 0; i < S.channels(); i++){
                    numer[i] = numerConst[i] + hvGradFreq[i] * beta;
                }

                vector<Mat> sFreq(S.channels());
                divComplexByRealMultiChannel(numer, denom, sFreq);

                idftMultiChannel(sFreq, S);

                beta = beta * kappa;
            }

            Mat D = dst.getMat();
            if(D.depth() == CV_8U)
            {
                S.convertTo(D, CV_8U, 255);
            }
            else if(D.depth() == CV_16U)
            {
                S.convertTo(D, CV_16U, 65535);
            }else if(D.depth() == CV_64F){
                S.convertTo(D, CV_64F);
            }else{
                S.copyTo(D);
            }
        }
예제 #21
0
파일: qff.cpp 프로젝트: johnkerl/spffl
// ----------------------------------------------------------------
bit_t bit_from_rat(intrat_t r)
{
	bit_t numer(r.get_numerator());
	bit_t denom(r.get_denominator());
	return numer / denom;
}
예제 #22
0
파일: convert.c 프로젝트: sageb0t/testsage
void t_FRAC_to_QQ ( mpq_t value, GEN g )
{
    t_INT_to_ZZ(mpq_numref(value), numer(g));
    t_INT_to_ZZ(mpq_denref(value), denom(g));
}
예제 #23
0
#include "boost/math/common_factor_rt.hpp"

//-----------------------------------------------------------------------------
#define cons  std::make_pair
const auto car = [](auto x) { return x.first; };
const auto cdr = [](auto x) { return x.second; };


//-----------------------------------------------------------------------------
// (define(add - rat x y)
//    (make-rat (+ (*(numer x) (denom y))
//                 (*(numer y) (denom x)))
//              (* (denom x) (denom y))))
const auto add_rat = [](auto x, auto y)
{
  return make_rat( (numer(x) * denom(y)) + (numer(y) * denom(x)),
                   denom(x) * denom(y));
};

//-----------------------------------------------------------------------------
// (define(sub - rat x y)
//    (make-rat (- (*(numer x) (denom y))
//                 (*(numer y) (denom x)))
//              (* (denom x) (denom y))))
const auto sub_rat = [](auto x, auto y)
{
  return make_rat( (numer(x) * denom(y)) - (numer(y) * denom(x)),
                   denom(x) * denom(y));
};

//-----------------------------------------------------------------------------
예제 #24
0
파일: mp-init.cpp 프로젝트: hznlp/pbmt
/*
 Extract initial phrase pairs and set cache pointers for each sentence pair
 Each entry in the phrase table contains two features:
 (prob,count) where prob = fractional count and count = absolute count*/
bool ExtractPhrasePairs(const string& src,
                        const string& tgt,
                        const string& out,
                        int max_sentence_length,
                        int max_phrase_length,
                        double max_length_ratio,
                        int min_phrase_count,
                        bool inmemory,
                        LexDic* lex_s2t,
                        LexDic* lex_t2s,
                        SimplePhraseTable& pt,
                        CorpusCache* cache){

    bool create_pt=pt.empty();
    if(src==""||tgt=="")return false;
    vector<vector<string>> src_corpus,tgt_corpus;
    vector<vector<int>> src_max_lens,tgt_max_lens;
    string log_prefix="";
    string logf="",loge="";
    if(log_prefix!=""){
        logf="log.f";
        loge="log.e";
    }

    PhraseCutoff(src,logf,&src_corpus,&src_max_lens,
                 max_phrase_length,min_phrase_count);
    PhraseCutoff(tgt,loge,&tgt_corpus,&tgt_max_lens,
                 max_phrase_length,min_phrase_count);

    vector<vector<double>> denom(100,vector<double>(100,0)),numer=denom;
    GenerateDenominator(denom);
    GenerateNumerator(numer);

    ofstream os(out.c_str());
    for(uint64_t sid=0;sid<src_corpus.size();sid++){
        vector<string>& ssent=src_corpus[sid];
        vector<string>& tsent=tgt_corpus[sid];
        int n=static_cast<int>(ssent.size());
        int m=static_cast<int>(tsent.size());
        if(n>max_sentence_length||m>max_sentence_length){
            continue;
        }
        if(cache!=nullptr)
            cache->push_back(
                SentenceCache((int)ssent.size(),(int)tsent.size(),5));

        vector<vector<vector<vector<double>>>> lexs2t_scores,lext2s_scores;
        if(lex_s2t&&lex_t2s&&create_pt){
            VScoreLex(ssent,tsent,*lex_s2t,lexs2t_scores,specs.prune_threshold);
            VScoreLex(tsent,ssent,*lex_t2s,lext2s_scores,specs.prune_threshold);
        }

        for(int i=0;i<(int)ssent.size();i++){
            for(int j=0;j<(int)tsent.size();j++){
                string sphrase="";
                for(int k=0;k<src_max_lens[sid][i];k++){
                    if(sphrase!="")sphrase+=" ";
                    sphrase+=ssent[i+k];
                    string tphrase="";
                    for(int l=0;l<tgt_max_lens[sid][j];l++){
                        if(tphrase!="")tphrase+=" ";
                        tphrase+=tsent[j+l];
                        if((k+1)>(((int)max_length_ratio)*(l+1))||
                           (l+1)>(((int)max_length_ratio)*(k+1))){
                            //cerr<<i<<" "<<k<<" "<<j<<" "<<l<<endl;
                            continue;
                        }
                        //cerr<<sphrase <<" ||| "<<tphrase
                        //<<" ||| "<<k+1<<" "<<l+1<<endl;
                        double prob=1E-5;
                        if(n-k-2>0&&m-l-2>0&&n>1&&m>1)
                            prob=numer[n-k-2][m-l-2]/denom[n-1][m-1];
                        if(!inmemory&&os.good())
                            os<<sphrase<<" ||| "<<tphrase
                              <<" ||| "<<prob<<" 1"<<endl;
                        else{
                            if(create_pt){
                                if(lex_s2t&&lex_t2s){
                                    double score_s2t=lexs2t_scores[i][k][j][l];
                                    double score_t2s=lext2s_scores[j][l][i][k];
/*
                                    cerr<<i<<" "<<k<<" "<<j<<" "<<l<<endl;
                                    cerr<<"new s2t "<<score_s2t<<endl;
                                    cerr<<"new t2s "<<score_t2s<<endl;
                                    score_s2t=VScoreLex(
                                        ssent,tsent,*lex_s2t,i,k,j,l);
                                    score_t2s=VScoreLex(
                                        tsent,ssent,*lex_t2s,j,l,i,k);
                                    cerr<<"old s2t "<<score_s2t<<endl;
                                    cerr<<"old t2s "<<score_t2s<<endl;
*/
                                    if(pow(score_s2t*score_t2s,1.0/(k+l+2))
                                       <=specs.prune_threshold){
                                        //cerr<<"score_s2t:"<<score_s2t
                                        //<<", score_t2s:"<<score_t2s<<endl;
                                        continue;
                                    }
                                }

                                auto& item=pt[sphrase][tphrase];
                                if(cache!=nullptr){
                                    cache->back()(i,k,j,l)=&item;
                                }
                                item.prob+=prob;
                                item.count+=1.0;
                            }
                            else{
                                if(k==0&&l==0){
                                    auto& item=pt[sphrase][tphrase];
                                    if(cache!=nullptr){
                                        cache->back()(i,k,j,l)=&item;
                                    }
                                    if(item.prob==0){
                                        item.prob=0.001;
                                        item.count=0.001;
                                    }
                                }
                                else{
                                    if(pt.find(sphrase)==pt.end())continue;
                                    auto& omap=pt[sphrase];
                                    auto iter=omap.find(tphrase);
                                    if(iter==omap.end())continue;
                                    /*
                                    cerr<<"found "<<sphrase<<" ||| "<<tphrase
                                        <<" ||| "<<iter->second.prob<<" "
                                        <<iter->second.count<<endl;*/
                                    cache->back()(i,k,j,l)=&(iter->second);
                                }
                            }
                        }
                    }
                }
            }
        }
        //cerr<<cache->back()(ssent.size(),4,tsent.size(),4)<<endl;
        //cerr<<sid<<endl;
    }
    if(inmemory&&os.good()){
        for(auto& m: pt)
            for(auto& i: m.second)
                os<<m.first<<" ||| "<<i.first<<" ||| "<<i.second.prob
                <<" "<<i.second.count<<endl;
    }
    os.close();
    return true;
}
예제 #25
0
void flop(_MIPD_ flash x,flash y,int *op,flash z)
{ /* Do basic flash operation - depending on   *
   * op[]. Performs operations of the form

              A.f1(x,y) + B.f2(x,y)
              -------------------
              C.f3(x,y) + D.f4(x,y)

   * Four functions f(x,y) are supported and    *
   * coded thus                                 *
   *              00 - Nx.Ny                    *
   *              01 - Nx.Dy                    *
   *              10 - Dx.Ny                    *
   *              11 - Dx.Dy                    *
   * where Nx is numerator of x, Dx denominator *
   * of x, etc.                                 *
   * op[0] contains the codes for f1-f4 in last *
   * eight bits =  00000000f1f2f3f4             *
   * op[1], op[2], op[3], op[4] contain the     *
   * single precision multipliers A, B, C, D    */
    int i,code;
#ifdef MR_OS_THREADS
    miracl *mr_mip=get_mip();
#endif
    if (mr_mip->ERNUM) return;

    MR_IN(69)
    numer(_MIPP_ x,mr_mip->w1);
    denom(_MIPP_ x,mr_mip->w2);
    numer(_MIPP_ y,mr_mip->w3);
    denom(_MIPP_ y,mr_mip->w4);

    mr_mip->check=OFF;
    for (i=1;i<=4;i++)
    {
        zero(mr_mip->w0);
        if (op[i]==0) continue;
        code=(op[0]>>(2*(4-i)))&3;
        switch (code)
        {
        case 0 : if (x==y) multiply(_MIPP_ mr_mip->w1,mr_mip->w1,mr_mip->w0);
                 else      multiply(_MIPP_ mr_mip->w1,mr_mip->w3,mr_mip->w0);
                 break;
        case 1 : multiply(_MIPP_ mr_mip->w1,mr_mip->w4,mr_mip->w0);
                 break;
        case 2 : multiply(_MIPP_ mr_mip->w2,mr_mip->w3,mr_mip->w0);
                 break;
        case 3 : if(x==y) multiply(_MIPP_ mr_mip->w2,mr_mip->w2,mr_mip->w0);
                 else     multiply(_MIPP_ mr_mip->w2,mr_mip->w4,mr_mip->w0);
                 break;
        }
        premult(_MIPP_ mr_mip->w0,op[i],mr_mip->w0);
        switch (i)
        {
        case 1 : copy(mr_mip->w0,mr_mip->w5);
                 break;
        case 2 : add(_MIPP_ mr_mip->w5,mr_mip->w0,mr_mip->w5);
                 break;
        case 3 : copy(mr_mip->w0,mr_mip->w6);
                 break;
        case 4 : add(_MIPP_ mr_mip->w6,mr_mip->w0,mr_mip->w6);
                 break;
        }
    }
    mr_mip->check=ON;
    mround(_MIPP_ mr_mip->w5,mr_mip->w6,z);
    MR_OUT
}
예제 #26
0
  std::vector<RingElem> BM_QQ(const SparsePolyRing& P, const ConstMatrixView& pts_in)
  {
    const long NumPts = NumRows(pts_in);
    const long dim = NumCols(pts_in);
    matrix pts = NewDenseMat(RingQQ(), NumPts, dim);
    for (long i=0; i < NumPts; ++i)
      for (long j=0; j < dim; ++j)
      {
        BigRat q;
        if (!IsRational(q, pts_in(i,j))) throw 999;
        SetEntry(pts,i,j, q);
      }

    // Ensure input pts have integer coords by using
    // scale factors for each indet.
    vector<BigInt> ScaleFactor(dim, BigInt(1));
    for (long j=0; j < dim; ++j)
      for (long i=0; i < NumPts; ++i)
        ScaleFactor[j] = lcm(ScaleFactor[j], ConvertTo<BigInt>(den(pts(i,j))));

    mpz_t **points = (mpz_t**)malloc(NumPts*sizeof(mpz_t*));
    for (long i=0; i < NumPts; ++i)
    {
      points[i] = (mpz_t*)malloc(dim*sizeof(mpz_t));
      for (long j=0; j < dim; ++j) mpz_init(points[i][j]);
      for (long j=0; j < dim; ++j)
      {
        mpz_set(points[i][j], mpzref(ConvertTo<BigInt>(ScaleFactor[j]*pts(i,j))));
      }
    }


    BMGB char0; // these will be "filled in" by BM_affine below
    BM modp;    //
            
    pp_cmp_PPM = &PPM(P); // not threadsafe!
    BM_affine(&char0, &modp, dim, NumPts, points, pp_cmp); // THIS CALL DOES THE REAL WORK!!!
    pp_cmp_PPM = NULL;
    for (long i=NumPts-1; i >=0 ; --i)
    {
      for (long j=0; j < dim; ++j) mpz_clear(points[i][j]);
      free(points[i]);
    }
    free(points);

    if (modp == NULL) { if (char0 != NULL) BMGB_dtor(char0); CoCoA_ERROR("Something went wrong", "BM_QQ"); }

    // Now extract the answer...
    const int GBsize = char0->GBsize;
    std::vector<RingElem> GB(GBsize);
    const long NumVars = dim;
    vector<long> expv(NumVars); // buffer for creating monomials
    for (int i=0; i < GBsize; ++i)
    {
      BigInt denom(1); // scale factor needed to make GB elem monic.
      for (int var = 0; var < NumVars; ++var)
      {
        expv[var] = modp->pp[modp->GB[i]][var];
        denom *= power(ScaleFactor[var], expv[var]);
      }
      RingElem GBelem = monomial(P, 1, expv);

      for (int j=0; j < NumPts; ++j)
      {
        if (mpq_sgn(char0->GB[i][j])==0) continue;
        BigRat c(char0->GB[i][j]);
        for (int var = 0; var < NumVars; ++var)
        {
          expv[var] = modp->pp[modp->sep[j]][var];
          c *= power(ScaleFactor[var], expv[var]);
        }
        GBelem += monomial(P, c/denom, expv);
      }
      GB[i] = GBelem;
    }
    BMGB_dtor(char0);
    BM_dtor(modp);
    return GB;
    // ignoring separators for the moment
  }
예제 #27
0
std::pair<unsigned int, Real>
EigenSystem::sensitivity_solve (const ParameterVector& parameters)
  {
    // make sure that eigensolution is already available
    libmesh_assert(_n_converged_eigenpairs);
    
    // the sensitivity is calculated based on the inner product of the left and
    // right eigen vectors.
    //
    //    y^T [A] x - lambda y^T [B] x = 0
    //    where y and x are the left and right eigenvectors
    //    d lambda/dp = (y^T (d[A]/dp - lambda d[B]/dp) x) / (y^T [B] x)
    //
    //    the denominator remain constant for all sensitivity calculations.
    //
    std::vector<Number> denom(_n_converged_eigenpairs, 0.),
    sens(_n_converged_eigenpairs, 0.);
    std::pair<Real, Real> eig_val;
    
    AutoPtr< NumericVector<Number> > x_right = NumericVector<Number>::build(this->comm()),
    x_left = NumericVector<Number>::build(this->comm()),
    tmp = NumericVector<Number>::build(this->comm());
    x_right->init(*solution); x_left->init(*solution); tmp->init(*solution);
    
    for (unsigned int i=0; i<_n_converged_eigenpairs; i++)
    {
      switch (_eigen_problem_type) {
        case HEP:
          // right and left eigenvectors are same
          // imaginary part of eigenvector for real matrices is zero
          this->eigen_solver->get_eigenpair(i, *x_right, NULL);
          denom[i] = x_right->dot(*x_right);               // x^H x
          break;
          
        case GHEP:
          // imaginary part of eigenvector for real matrices is zero
          this->eigen_solver->get_eigenpair(i, *x_right, NULL);
          matrix_B->vector_mult(*tmp, *x_right);
          denom[i] = x_right->dot(*tmp);                  // x^H B x
          
        default:
          // to be implemented for the non-Hermitian problems
          libmesh_error();
          break;
      }
    }
    
    for (unsigned int p=0; p<parameters.size(); p++)
    {
      // calculate sensitivity of matrix quantities
      this->assemble_eigensystem_sensitivity(parameters, p);
      
      // now calculate sensitivity of each eigenvalue for the parameter
      for (unsigned int i=0; i<_n_converged_eigenpairs; i++)
      {
        eig_val = this->eigen_solver->get_eigenpair(i, *x_right);
        switch (_eigen_problem_type)
        {
          case HEP:
            matrix_A->vector_mult(*tmp, *x_right);
            sens[i] = x_right->dot(*tmp);            // x^H A' x
            sens[i] /= denom[i];                     // x^H x
            break;

          case GHEP:
            matrix_A->vector_mult(*tmp, *x_right);
            sens[i] = x_right->dot(*tmp);                 // x^H A' x
            matrix_B->vector_mult(*tmp, *x_right);
            sens[i]-= eig_val.first * x_right->dot(*tmp); // - lambda x^H B' x
            sens[i] /= denom[i];                          // x^H B x
            break;
            
          default:
            // to be implemented for the non-Hermitian problems
            libmesh_error();
            break;
        }
      }
    }
    
    return std::pair<unsigned int, Real> (0, 0.);
  }
예제 #28
0
파일: Utm.cpp 프로젝트: LK8000/LK8000
double sphsr (double a, double es, double sphi)
{
	double dn = denom (es, sphi);
	return a * (1.0 - es) / (dn * dn * dn);
}
예제 #29
0
void NavEstimator::update()
{
    Eigen::MatrixXf I_p;
    I_p = Eigen::MatrixXf::Identity(7,7);
    Eigen::MatrixXf denom(1,1);

    if(input.gps_new)
    {
        input.gps_new = false;

        // gps North position
        h_p = xhat_p(0);
        C_p = Eigen::VectorXf::Zero(7);
        C_p(0) = 1;
        denom(0,0) = (R_p(0,0) + (C_p.transpose()*P_p*C_p)(0,0));
        L_p = (P_p*C_p) * denom.inverse();
        P_p = (I_p - L_p*C_p.transpose())*P_p;
        xhat_p = xhat_p + L_p*(input.gps_n - h_p);

        // gps East position
        h_p = xhat_p(1);
        C_p = Eigen::VectorXf::Zero(7);
        C_p(1) = 1;
        denom(0,0) = (R_p(1,1) + (C_p.transpose()*P_p*C_p)(0,0));
        L_p = (P_p*C_p) * denom.inverse();
        P_p = (I_p - L_p*C_p.transpose())*P_p;
        xhat_p = xhat_p + L_p*(input.gps_e - h_p);
    }

    if(input.gps_vel_new)
    {
        input.gps_vel_new = false;

        // gps ground speed
        h_p = xhat_p(2);
        C_p = Eigen::VectorXf::Zero(7);
        C_p(2) = 1;
        denom(0,0) = (R_p(2,2) + (C_p.transpose()*P_p*C_p)(0,0));
        L_p = (P_p*C_p) * denom.inverse();
        P_p = (I_p - L_p*C_p.transpose())*P_p;
        xhat_p = xhat_p + L_p*(input.gps_Vg - h_p);

        // gps course
        //wrap course measurement
        float gps_course = fmodf(input.gps_course, fradians(360.0f));

        while(gps_course - xhat_p(3) > fradians(180.0f)) gps_course = gps_course - fradians(360.0f);
        while(gps_course - xhat_p(3) < fradians(-180.0f)) gps_course = gps_course + fradians(360.0f);
        h_p = xhat_p(3);
        C_p = Eigen::VectorXf::Zero(7);
        C_p(3) = 1;
        denom(0,0) = (R_p(3,3) + (C_p.transpose()*P_p*C_p)(0,0));
        L_p = (P_p*C_p) * denom.inverse();
        P_p = (I_p - L_p*C_p.transpose())*P_p;
        xhat_p = xhat_p + L_p*(gps_course - h_p);
    }

    if(xhat_p(0) > 3000 || xhat_p(0) < -3000 || xhat_p(1) > 3000 || xhat_p(1) < -3000)
        gps_initialized_ = false;

    for(int i=0;i<7;i++)
    {
        if(xhat_p(i) != xhat_p(i))
        {
            initialize();

            switch(i)
            {
            case 0:
                xhat_p(i) = input.gps_n;
                break;
            case 1:
                xhat_p(i) = input.gps_e;
                break;
            case 2:
                xhat_p(i) = input.gps_Vg;
                break;
            case 3:
                xhat_p(i) = psihat;
                break;
            case 6:
                xhat_p(i) = psihat;
                break;
            default:
                xhat_p(i) = 0;
            }
        }
    }
}