Пример #1
0
int DecimalDecNumber::sign() const
{
   if (isNegative())
      return -1;
   else if (isZero())
      return 0;
   return 1;
}
Пример #2
0
std::string
SignedInteger<MD, DT, NT>::toString() const
{
    if (isNegative())
        return(std::string("-")+number_.toString());
    else
        return(number_.toString());
}
Пример #3
0
unsigned int executeAlu(statusType stat)
{
  unsigned int a = getAluA();
  unsigned int b = getAluB();
  unsigned int fun = getAluFun();
  unsigned int result = 0;

  switch (fun)
  {
    case FADDL:
      result = a + b;
      break;

    case FSUBL:
      result = b - a;
      break;

    case FANDL:
      result = a & b;
      break;

    case FXORL:
      result = a ^ b;
      break;
  }

  if (needToSetCC(stat))
  {
    unsigned int isZero = result == 0;
    unsigned int isSigned = isNegative(result);
    unsigned int isOverflow = 0;

    if (fun == FADDL)
    {
      isOverflow = (isNegative(a) == isNegative(b)) &&
        (isNegative(result) != isNegative(a));
    }
    else if (fun == FSUBL)
    {
      isOverflow = (isNegative(a) != isNegative(b)) &&
        (isNegative(result) == isNegative(a));
    }

    setCC(ZF, isZero);
    setCC(SF, isSigned);
    setCC(OF, isOverflow);
  }

  return result;
}
Пример #4
0
         void numberInputWindow::stripLeadingZeros()
         {
            t_int n = 0;
            std::string::const_iterator leading_iter = input_.begin();
            if (isNegative())
               {
                  leading_iter++;
               }

            if (leading_iter == input_.end())
               {
                  return;
               }

            for (; leading_iter != input_.end(); leading_iter++)
               {
                  if (*leading_iter == '0')
                     {
                        n++;
                     }
                  else
                     {
                        break;
                     }
               }

            if (n > 1)
               {
                  std::string::iterator iter = input_.begin();
                  if (isNegative())
                     {
                        iter++;
                     }

                  if (iter != input_.end())
                     {
                        for (t_int i = 0; i < (n-1); i++)
                           {
                              input_.erase(iter++);
                              changed_ = true;
                           }
                     }
               }
         }
Пример #5
0
unsigned int
floatToUint (float f)
{
    if (isNegative (f) || isNan (f))
	return 0;

    if (isInfinity (f) || f > UINT_MAX)
	return UINT_MAX;

    return (unsigned int) f;
}
Пример #6
0
bool
SignedInteger<MD, DT, NT>::operator>(const SignedInteger<MD, DT, NT> &n) const
{
    if (isNegative() && n.isPositive())
        return(false);
    else if (isPositive() && n.isNegative())
        return(true);
    else if (isPositive())
        return number_ > n.number_;
    else
        return number_ < n.number_;
}
Пример #7
0
double
CQRealSpin::
posToStep(int pos) const
{
  bool negative = isNegative();

  int dotPos = this->dotPos();

  //---

  // if no dot then power is length - pos
  if (dotPos < 0) {
    if (! negative) {
      if (pos < 1)
        pos = 1;
    }
    else {
      if (pos < 2)
        pos = 2;
    }

    int d = text().length() - pos;

    return pow(10, d);
  }

  //---

  // dot on right (1)
  if (pos == dotPos)
    return 1;

  //---

  // dot on left (0.1)
  if (pos == dotPos + 1)
    return 0.1;

  if (! negative) {
    if (pos < 1)
      pos = 1;
  }
  else {
    if (pos < 2)
      pos = 2;
  }

  if (pos > dotPos)
    --pos;

  return pow(10, dotPos - pos);
}
Пример #8
0
Vec3D<> CVX_Voxel::moment()
{
	//moments from internal bonds
	Vec3D<> totalMoment(0,0,0);
	for (int i=0; i<6; i++){ 
		if (links[i]) totalMoment += links[i]->moment(isNegative((linkDirection)i)); //total force in LCS
	}
	totalMoment = orient.RotateVec3D(totalMoment);
	
	//other moments
	totalMoment += extMoment; //external moments
	totalMoment -= angularVelocity()*mat->globalDampingRotateC(); //global damping
	return totalMoment;
}
Пример #9
0
/** Returns the floor of this Numeric */
Numeric::Ptr ATFloatOrDerivedImpl::floor(const DynamicContext* context) const {
  switch (_state) {
    case NaN: return notANumber(context);
    case INF: return infinity(context);
    case NEG_INF: return negInfinity(context);
    case NEG_NUM:
    case NUM: { 
      if (isZero() && isNegative())
        return negZero(context);
      return newFloat(_float.floor(), context); 
    }
    default: { assert(false); return 0; // should never get here 
    }
  }
}
Пример #10
0
void DlSatTester :: logStartEntry ( void ) const
{
	CHECK_LL_RETURN(llGTA);	// useless but safe
	logIndentation();
	LL << "(";
	curNode->logNode ();
	LL << "," << curConcept << "){";
	if ( isNegative (curConcept.bp()) )
		LL << "~";
	const DLVertex& v = DLHeap[curConcept];
	LL << v.getTagName();
	if ( const TNamedEntry* entry = v.getConcept() )
		LL << "(" << entry->getName() << ")";
	LL << "}:";
}
Пример #11
0
	// Tests randomness of the BaseCryptoRandomStream and returns the random value
	bool RunsTest::IsRandom(BaseCryptoRandomStream* bitStream) {
		unsigned long int i;
		unsigned short int *r;
		double product, sum;
	
		if (bitStream->GetBitLength() < this->GetMinimumLength()) {
			this->error = InsufficientNumberOfBits;
			this->random = false;
			return this->random;
		}
		bitStream->SetBitPosition(0);
		this->error = NoError;
		if ((r = (unsigned short int *) calloc(bitStream->GetBitLength(),sizeof(unsigned short int))) == NULL) {
			this->error = InsufficientMemory;
			this->random = false;
		}
		else {
			sum = 0.0;
			for(i = 0; i < bitStream->GetBitLength(); i++)
				sum += (int)bitStream->GetBitForward();
			this->pi = sum/bitStream->GetBitLength();
			for(i = 0; i < bitStream->GetBitLength()-1; i++) {
				if ((int)bitStream->GetBitPosition(i) == (int)bitStream->GetBitPosition(i+1))
					r[i] = 0;
				else
					r[i] = 1;
			} 
			this->totalNumberRuns = 0;
			for(i = 0; i < bitStream->GetBitLength()-1; i++)
	        	this->totalNumberRuns += r[i];
		    this->totalNumberRuns++;
			product = this->pi * (1.e0 - this->pi);
			this->argument = fabs(this->totalNumberRuns - 2.e0*bitStream->GetBitLength()*product)/(2.e0*sqrt(2.e0*bitStream->GetBitLength())*product);
			this->pValue = this->mathFuncs->ErFc(this->argument);
			if (this->pValue < this->alpha) {				    
				this->random = false;
			}
			else {
				this->random = true;
			}
			free(r);
			if (isNegative(this->pValue) || isGreaterThanOne(this->pValue)) {
				this->random = false;
		        this->error = PValueOutOfRange;
			}
		}
		return this->random;
	}
//-----------------------------------------------------------------------------
// bool PMTVMedia_MovieRatingFilter::isOk(PMTVMedia_Media* media)
// Test si 'media' a le rating demandé (ou non si neg est activé)
//-----------------------------------------------------------------------------
bool PMTVMedia_MovieRatingFilter::isOk(PMTVMedia_Media* media)
{
    PMTVMedia_MediaInfo* mediaInfo = media->getMediaInfo();
    
    // Film?
    if(mediaInfo->getMediaType() == PMTVMEDIATYPE_MOVIE)
    {
        // Récupération du rating et filtre
        bool ok = ((PMTVMedia_MovieInfo*)mediaInfo)->getMovieRating() == m_rating;
        if(isNegative())
        { ok = !ok; }
        return ok;
    }
    else // Pas un film on s'en fou
    { return true; }
}
Пример #13
0
void BigReal::save(ByteOutputStream &s) const {
  BYTE b = 0;
  if(isZero()) {
    b = ZERO_FLAG;
  } else if(isNegative()) {
    b = NEGATIVE_FLAG;
  }
  s.putByte(b);
  if(!isZero()) {
    s.putBytes((BYTE*)&m_expo, sizeof(m_expo));
    const size_t length = getLength();
    s.putBytes((BYTE*)&length, sizeof(length));
    for(Digit *p = m_first; p; p = p->next) {
      s.putBytes((BYTE*)&(p->n), sizeof(p->n));
    }
  }
}
Double80 BigReal::getDouble80NoLimitCheck() const {
  static const int minExpo2 = 64-16382;
  static const int maxExpo2 = 0x3fff;

  DigitPool       *pool  = getDigitPool();
  const BRExpoType ee2   = getExpo2(*this);
  const BRExpoType expo2 = 64 - ee2;
  bool             e2Overflow;
  Double80         e2, e2x;
  BigReal          xi(pool);
  if(expo2 <= minExpo2) {
    e2 = Double80::pow2(minExpo2);
    e2Overflow = false;
    xi.shortProduct(::cut(*this,21), pow2(minExpo2, CONVERSION_POW2DIGITCOUNT), BIGREAL_ESCEXPO);  // BigReal multiplication
  } else if(expo2 >= maxExpo2) {
    e2  = Double80::pow2(maxExpo2);
    e2x = Double80::pow2((int)expo2 - maxExpo2);
    e2Overflow = true;
    xi.shortProduct(::cut(*this,21), pow2((int)expo2, CONVERSION_POW2DIGITCOUNT), BIGREAL_ESCEXPO);  // BigReal multiplication
  } else {
    e2 = Double80::pow2((int)expo2);
    e2Overflow = false;
    xi = round(xi.shortProduct(::cut(*this,22), pow2((int)expo2, CONVERSION_POW2DIGITCOUNT), -1));  // BigReal multiplication
  }
  const Digit *p = xi.m_first;
  if(p == NULL) {
    return Double80::zero;
  }
  Double80 result     = (INT64)p->n;
  int      digitCount = LOG10_BIGREALBASE;
  for(p = p->next; p && (digitCount < 24); p = p->next, digitCount += LOG10_BIGREALBASE) {
    result *= BIGREALBASE;
    result += (INT64)p->n;
  }
  const BRExpoType e = xi.m_expo * LOG10_BIGREALBASE - digitCount + LOG10_BIGREALBASE;
  if(e > 0) {
    result *= Double80::pow10((int)e);
  } else if(e < 0) {
    result /= Double80::pow10(-(int)e);
  }
  result /= e2;
  if(e2Overflow) {
    result /= e2x;
  }
  return isNegative() ? -result : result;
}
Пример #15
0
//////////////////////////////////////////////////////////////////////////////
///
///	Convert an array of character into a number
///
//////////////////////////////////////////////////////////////////////////////
long controller::convertCharacterToNumber(unsigned char* ptr,
  unsigned char length) {
 unsigned char i;
 unsigned long number = 0;
 bool isNegativeNumber = false;

 for (i = 0; i < length; i++) {
  if (isNegative(ptr[i])) {
   isNegativeNumber = true;
   continue;
  }

  number += atoi(ptr[i]) * pow(10, length - i - 1);
 }

 return isNegativeNumber ? number * -1 : number;
}
Пример #16
0
/** Rounds this Numeric to the given precision, and rounds a half to even */
Numeric::Ptr ATFloatOrDerivedImpl::roundHalfToEven(const Numeric::Ptr &precision, const DynamicContext* context) const {
    switch (_state) {
    case NaN:
        return notANumber(context);
    case INF:
        return infinity(context);
    case NEG_INF:
        return negInfinity(context);
    case NEG_NUM:
    case NUM:
        break;
    default: {
        assert(false);
        return 0; // should never get here
    }
    }

    if (isZero() && isNegative())
        return this;

    ATFloatOrDerived::Ptr float_precision = (const Numeric::Ptr)precision->castAs(this->getPrimitiveTypeIndex(), context);
    MAPM exp = MAPM(10).pow(((ATFloatOrDerivedImpl*)(const ATFloatOrDerived*)float_precision)->_float);
    MAPM value = _float * exp;
    bool halfVal = false;

    // check if we're rounding on a half value
    if((value-0.5) == (value.floor())) {
        halfVal = true;
    }
    value = _float * exp + 0.5;
    value = value.floor();

    // if halfVal make sure what we return has the least significant digit even
    if (halfVal) {
        if(value.is_odd()) {
            value = value - 1;
        }
    }
    value = value / exp;

    // the spec doesn't actually say to do this, but djf believes this is the correct way to handle rounding of -ve values which will result in 0.0E0
    // if (value == 0 && isNegative())
    // return negZero(context);
    return newFloat(value, context);
}
Пример #17
0
Vec3D<> CVX_Voxel::force()
{
	//forces from internal bonds
	Vec3D<> totalForce(0,0,0);
	for (int i=0; i<6; i++){ 
		if (links[i]) totalForce += links[i]->force(isNegative((linkDirection)i)); //total force in LCS
	}
	totalForce = orient.RotateVec3D(totalForce);

	//other forces
	totalForce += extForce; //external forces
	totalForce -= velocity()*mat->globalDampingTranslateC(); //global damping
	if (isGravityEnabled()) totalForce.z -= mat->_mass*9.80665; //gravity, according to f=mg
	if (isFloorEnabled()) addFloorForces(&totalForce); //adds forces from interacting with the floor
	//Collisions: todo

	return totalForce;
}
	// Tests randomness of the BaseCryptoRandomStream and returns the random value
	bool CumulativeSumReverseTest::IsRandom(BaseCryptoRandomStream* bitStream) {
		signed long int i, k, start, finish;
		double z, sum, sum1, sum2;
 
		if (bitStream->GetBitLength() < this->GetMinimumLength()) {
			this->error = InsufficientNumberOfBits;
			this->random = false;
			return this->random;
		}
		bitStream->SetBitPosition(bitStream->GetBitLength() -1);
		this->error = NoError;
		sum = 0.0;
		this->cuSum = 1;
		for(i = bitStream->GetBitLength() -1; i >= 0; i--) {
			sum += 2*(int)bitStream->GetBitReverse() - 1;
    		this->cuSum = MAX(this->cuSum, fabs(sum));
		}
		z = this->cuSum;
		sum1 = 0.0;
		start = (-(long)bitStream->GetBitLength()/(int)z+1)/4;
		finish = (bitStream->GetBitLength()/(int)z-1)/4;
		for(k = start; k <= finish; k++)
			sum1 += (this->mathFuncs->Normal((4*k+1)*z/sqrt((double)bitStream->GetBitLength()))-this->mathFuncs->Normal((4*k-1)*z/sqrt((double)bitStream->GetBitLength())));
		sum2 = 0.0;
		start = (-(long)bitStream->GetBitLength()/(int)z-3)/4;
		finish = (bitStream->GetBitLength()/(int)z-1)/4;
		for(k = start; k <= finish; k++)
			sum2 += (this->mathFuncs->Normal((4*k+3)*z/sqrt((double)bitStream->GetBitLength()))-this->mathFuncs->Normal((4*k+1)*z/sqrt((double)bitStream->GetBitLength())));
		this->pValue = 1.0 - sum1 + sum2;
		if (isNegative(this->pValue) || isGreaterThanOne(this->pValue)) {
			this->error = PValueOutOfRange;
    		this->random = false; 
		}
		else {
			if (this->pValue < this->alpha) { 
        		this->random = false; 
			}
			else {
				this->random = true; 
			}
		}
		return this->random;
	}
Пример #19
0
//////////////////////////////////////////////////////////////////////////////
///
///	Make sure it is a number
///
//////////////////////////////////////////////////////////////////////////////
bool controller::isNumber(unsigned char* ptr, unsigned char length) {
 bool isFirstCharacter = true;
 int i;

 for (i = 0; i < length; i++) {
  if (isSpace(ptr[i]))
   return false;

  if (isFirstCharacter && !isDigit(ptr[i]) && !isNegative(ptr[i]))
   return false;

  if (!isFirstCharacter && !isDigit(ptr[i]))
   return false;

  isFirstCharacter = false;
 }

 return true;
}
Пример #20
0
int main (void) {
    printf("%d\n", 01777);// eight digit hex
    printf("%d\n", 0x1777); // 16 digit hex

    typeLength();
    outputControllSymbol();
    printf("%d\n", TOP);
    printf("%d\n", SINT_MAX);

    char* pDest;
    StrCpy(pDest, "hello world!");
    printf("%s\n", pDest);

    printConst();
    printf("%d\n", isNegative(200));
    printf("%c\n", (char)300324);
    variableScope();
    pointer();
    printStruct();
    return 0;
}
Пример #21
0
Vec3D<> CVX_Voxel::strain(bool tensionStrain) const
{
	//if no connections in the positive and negative directions of a particular axis, strain is zero
	//if one connection in positive or negative direction of a particular axis, strain is that strain - ?? and force or constraint?
	//if connections in both the positive and negative directions of a particular axis, strain is the average. 
	Vec3D<> intStrRet(0,0,0); //intermediate strain return value. axes according to linkAxis enum
	int numBondAxis[3] = {0}; //number of bonds in this axis (0,1,2). axes according to linkAxis enum
	for (int i=0; i<6; i++){ //cycle through link directions
		if (links[i]){
			int axis = toAxis((linkDirection)i);
			intStrRet[axis] += links[i]->axialStrain(isNegative((linkDirection)i));
			numBondAxis[axis]++;
		}
	}
	for (int i=0; i<3; i++){ //cycle through axes
		if (numBondAxis[i]==2) intStrRet[i] *= 0.5f; //average
		if (tensionStrain && numBondAxis[i]==1){ //if just one bond
			if (!dofIsSet(dofFixed, (dofComponent)i) && extForce[i] == 0) intStrRet[i]=0; //if no other external means of providing tension, zero out strain.
		}
	}

	return intStrRet;
}
Пример #22
0
Period Period::parse(const StreamPos &pos,
                     std::string::const_iterator begin,
                     std::string::const_iterator end)
{
    auto slash = std::find(begin, end, '/');
    /* second part (after the slash) must have at least one character: */
    if (end - slash < 2) {
        throw ParserException(pos, "Invalid period value!");
    }
    auto startTime = DateTime::parse(pos, begin, slash);
    char firstCharOfSecondPart = *(slash + 1);
    if (firstCharOfSecondPart == '-' || firstCharOfSecondPart == '+' ||
            firstCharOfSecondPart == 'P') {
        auto duration = Duration::parse(pos, slash + 1, end);
        if (duration.isNegative()) {
            throw ParserException(pos, "Period duration must be positive!");
        }
        return { startTime, duration };
    } else {
        auto endTime = DateTime::parse(pos, slash + 1, end);
        return { startTime, endTime };
    }
}
Пример #23
0
void
CQRealSpin::
stepBy(int n)
{
  lineEdit()->deselect();

  //---

  double v = value();
  double s = step();

  int pos    = cursorPosition();
  int dotPos = this->dotPos();

  bool negative = isNegative();

  if (! negative) {
    if (pos < 1)
      pos = 1;
  }
  else {
    if (pos < 2)
      pos = 2;
  }

  setValue(v + n*s);

  int dotPos1 = this->dotPos();

  int pos1 = dotPos1 - dotPos + pos;

  if (pos1 != pos)
    setCursorPosition(pos1);

  updateStep();
}
Пример #24
0
void
LongestRunOfOnes(int n)
{
	double			pval, chi2, pi[7];
	int				run, v_n_obs, N, i, j, K, M, V[7];
	unsigned int	nu[7] = { 0, 0, 0, 0, 0, 0, 0 };

	if ( n < 128 ) {
		fprintf(stats[TEST_LONGEST_RUN], "\t\t\t  LONGEST RUNS OF ONES TEST\n");
		fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
		fprintf(stats[TEST_LONGEST_RUN], "\t\t   n=%d is too short\n", n);
		return;
	}
	if ( n < 6272 ) {
		K = 3;
		M = 8;
		V[0] = 1; V[1] = 2; V[2] = 3; V[3] = 4;
		pi[0] = 0.21484375;
		pi[1] = 0.3671875;
		pi[2] = 0.23046875;
		pi[3] = 0.1875;
	}
	else if ( n < 750000 ) {
		K = 5;
		M = 128;
		V[0] = 4; V[1] = 5; V[2] = 6; V[3] = 7; V[4] = 8; V[5] = 9;
		pi[0] = 0.1174035788;
		pi[1] = 0.242955959;
		pi[2] = 0.249363483;
		pi[3] = 0.17517706;
		pi[4] = 0.102701071;
		pi[5] = 0.112398847;
	}
	else {
		K = 6;
		M = 10000;
			V[0] = 10; V[1] = 11; V[2] = 12; V[3] = 13; V[4] = 14; V[5] = 15; V[6] = 16;
		pi[0] = 0.0882;
		pi[1] = 0.2092;
		pi[2] = 0.2483;
		pi[3] = 0.1933;
		pi[4] = 0.1208;
		pi[5] = 0.0675;
		pi[6] = 0.0727;
	}
	
	N = n/M;
	for ( i=0; i<N; i++ ) {
		v_n_obs = 0;
		run = 0;
		for ( j=0; j<M; j++ ) {
			if ( epsilon[i*M+j] == 1 ) {
				run++;
				if ( run > v_n_obs )
					v_n_obs = run;
			}
			else
				run = 0;
		}
		if ( v_n_obs < V[0] )
			nu[0]++;
		for ( j=0; j<=K; j++ ) {
			if ( v_n_obs == V[j] )
				nu[j]++;
		}
		if ( v_n_obs > V[K] )
			nu[K]++;
	}

	chi2 = 0.0;
	for ( i=0; i<=K; i++ )
		chi2 += ((nu[i] - N * pi[i]) * (nu[i] - N * pi[i])) / (N * pi[i]);

	pval = cephes_igamc((double)(K/2.0), chi2 / 2.0);

	fprintf(stats[TEST_LONGEST_RUN], "\t\t\t  LONGEST RUNS OF ONES TEST\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\tCOMPUTATIONAL INFORMATION:\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\t(a) N (# of substrings)  = %d\n", N);
	fprintf(stats[TEST_LONGEST_RUN], "\t\t(b) M (Substring Length) = %d\n", M);
	fprintf(stats[TEST_LONGEST_RUN], "\t\t(c) Chi^2                = %f\n", chi2);
	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\t      F R E Q U E N C Y\n");
	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");

	if ( K == 3 ) {
		fprintf(stats[TEST_LONGEST_RUN], "\t\t  <=1     2     3    >=4   P-value  Assignment");
		fprintf(stats[TEST_LONGEST_RUN], "\n\t\t %3d %3d %3d  %3d ", nu[0], nu[1], nu[2], nu[3]);
	}
	else if ( K == 5 ) {
		fprintf(stats[TEST_LONGEST_RUN], "\t\t<=4  5  6  7  8  >=9 P-value  Assignment");
		fprintf(stats[TEST_LONGEST_RUN], "\n\t\t %3d %3d %3d %3d %3d  %3d ", nu[0], nu[1], nu[2],
				nu[3], nu[4], nu[5]);
	}
	else {
		fprintf(stats[TEST_LONGEST_RUN],"\t\t<=10  11  12  13  14  15 >=16 P-value  Assignment");
		fprintf(stats[TEST_LONGEST_RUN],"\n\t\t %3d %3d %3d %3d %3d %3d  %3d ", nu[0], nu[1], nu[2],
				nu[3], nu[4], nu[5], nu[6]);
	}
	if ( isNegative(pval) || isGreaterThanOne(pval) )
		fprintf(stats[TEST_LONGEST_RUN], "WARNING:  P_VALUE IS OUT OF RANGE.\n");

	fprintf(stats[TEST_LONGEST_RUN], "%s\t\tp_value = %f\n\n", pval < ALPHA ? "FAILURE" : "SUCCESS", pval); fflush(stats[TEST_LONGEST_RUN]);
	fprintf(results[TEST_LONGEST_RUN], "%f\n", pval); fflush(results[TEST_LONGEST_RUN]);
}
Пример #25
0
void BaseInputRewriter::translateChoice(Rule*& rule,vector<Rule*>& ruleRewrited) {

	unsigned id=IdGenerator::getInstance()->getId();
	unsigned counter=1;

	// Create an auxiliary rule in order to ground the body only once.
	// First the variables shared between the atoms in the body
	// and the choice atom are found, these variables will be
	// the term of the auxiliary atom in the head of the auxiliary rule

	Atom* choice =rule->getAtomInHead(0);

	Atom *auxiliaryAtomBody=nullptr;
	if(rule->getSizeBody()>1){

		set_term variables_in_choice=choice->getVariable();
		set_term variables_in_body;

		for(unsigned i=0;i<rule->getSizeBody();++i){
			auto atom=rule->getAtomInBody(i);
			if(atom->isNegative())continue;
			set_term variables;
			if(atom->isAggregateAtom())
				variables=atom->getGuardVariable();
			else
				variables=atom->getVariable();
			variables_in_body.insert(variables.begin(),variables.end());
		}

		set_term variables_intersection;
		Utils::intersectionSet(variables_in_choice,variables_in_body,variables_intersection);

		Rule * body_rule=new Rule;

		if(rule->isMustBeRewritedForAggregates()) body_rule->setMustBeRewritedForAggregates(true);

		//Body
		body_rule->setBody(rule->getBody());

		//Head
		string predicate_name=AUXILIARY+SEPARATOR+to_string(id)+SEPARATOR+to_string(counter);
		vector<Term*> terms(variables_intersection.begin(),variables_intersection.end());
		auxiliaryAtomBody=generateNewAuxiliaryAtom(predicate_name,terms);
		body_rule->addInHead(auxiliaryAtomBody);

		ruleRewrited.push_back(body_rule);
		counter++;

	}else{
		if(rule->getSizeBody()==1)
			auxiliaryAtomBody=rule->getAtomInBody(0);
	}

	// For each choice element a new disjunctive auxiliary rule is created.
	// Each rule has in the head a disjunction with a the first atom of the choice element and a new auxiliary atom
	// having the same terms of the first atom, while in the body it contains the remaining atoms of the choice element
	// and the auxiliary atom previously created for the body.
	// Also, the aggregate elements for the constraint rule are created (see below)
	vector<AggregateElement*> elements = rewriteChoiceElements(id, counter,choice, auxiliaryAtomBody, ruleRewrited);

	// Finally a constraint rule is created.
	// It has as body the auxiliary atom previously created for the body, and a negated count aggregate
	// whose guard are the same of the choice atom and inside contains the first atom of each choice element
	// and as aggregate terms all its terms
	rewriteChoiceConstraint(elements, auxiliaryAtomBody, choice, ruleRewrited);

	if(rule->getSizeBody()==1)
		delete auxiliaryAtomBody;

	rule->deleteBody([](Atom* atom){
		return 0;
	});
	rule->deleteHead([](Atom* atom){
		return 1;
	});
	delete rule;
	rule=0;
}
Пример #26
0
Pointer<Number> RealNumber::getAbsoluteValue() const{
	if(isNegative()) return this->getNegation();
	else return this->copy();
}
Пример #27
0
void
Rank(int n)
{
	int			N, i, k, r;
	double		p_value, product, chi_squared, arg1, p_32, p_31, p_30, R, F_32, F_31, F_30;
	BitSequence	**matrix = create_matrix(32, 32);
	
	N = n/(32*32);
	if ( isZero(N) ) {
		fprintf(stats[TEST_RANK], "\t\t\t\tRANK TEST\n");
		fprintf(stats[TEST_RANK], "\t\tError: Insuffucient # Of Bits To Define An 32x32 (%dx%d) Matrix\n", 32, 32);
		p_value = 0.00;
	}
	else {
		r = 32;					/* COMPUTE PROBABILITIES */
		product = 1;
		for ( i=0; i<=r-1; i++ )
			product *= ((1.e0-pow(2, i-32))*(1.e0-pow(2, i-32)))/(1.e0-pow(2, i-r));
		p_32 = pow(2, r*(32+32-r)-32*32) * product;
		
		r = 31;
		product = 1;
		for ( i=0; i<=r-1; i++ )
			product *= ((1.e0-pow(2, i-32))*(1.e0-pow(2, i-32)))/(1.e0-pow(2, i-r));
		p_31 = pow(2, r*(32+32-r)-32*32) * product;
		
		p_30 = 1 - (p_32+p_31);
		
		F_32 = 0;
		F_31 = 0;
		for ( k=0; k<N; k++ ) {			/* FOR EACH 32x32 MATRIX   */
			def_matrix(32, 32, matrix, k);
#if (DISPLAY_MATRICES == 1)
			display_matrix(32, 32, matrix);
#endif
			R = computeRank(32, 32, matrix);
			if ( R == 32 )
				F_32++;			/* DETERMINE FREQUENCIES */
			if ( R == 31 )
				F_31++;
		}
		F_30 = (double)N - (F_32+F_31);
		
		chi_squared =(pow(F_32 - N*p_32, 2)/(double)(N*p_32) +
					  pow(F_31 - N*p_31, 2)/(double)(N*p_31) +
					  pow(F_30 - N*p_30, 2)/(double)(N*p_30));
		
		arg1 = -chi_squared/2.e0;

		fprintf(stats[TEST_RANK], "\t\t\t\tRANK TEST\n");
		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");
		fprintf(stats[TEST_RANK], "\t\tCOMPUTATIONAL INFORMATION:\n");
		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");
		fprintf(stats[TEST_RANK], "\t\t(a) Probability P_%d = %f\n", 32,p_32);
		fprintf(stats[TEST_RANK], "\t\t(b)             P_%d = %f\n", 31,p_31);
		fprintf(stats[TEST_RANK], "\t\t(c)             P_%d = %f\n", 30,p_30);
		fprintf(stats[TEST_RANK], "\t\t(d) Frequency   F_%d = %d\n", 32,(int)F_32);
		fprintf(stats[TEST_RANK], "\t\t(e)             F_%d = %d\n", 31,(int)F_31);
		fprintf(stats[TEST_RANK], "\t\t(f)             F_%d = %d\n", 30,(int)F_30);
		fprintf(stats[TEST_RANK], "\t\t(g) # of matrices    = %d\n", N);
		fprintf(stats[TEST_RANK], "\t\t(h) Chi^2            = %f\n", chi_squared);
		fprintf(stats[TEST_RANK], "\t\t(i) NOTE: %d BITS WERE DISCARDED.\n", n%(32*32));
		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");

		p_value = exp(arg1);
		if ( isNegative(p_value) || isGreaterThanOne(p_value) )
			fprintf(stats[TEST_RANK], "WARNING:  P_VALUE IS OUT OF RANGE.\n");

		for ( i=0; i<32; i++ )				/* DEALLOCATE MATRIX  */
			free(matrix[i]);
		free(matrix);
	}
	fprintf(stats[TEST_RANK], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value); fflush(stats[TEST_RANK]);
	fprintf(results[TEST_RANK], "%f\n", p_value); fflush(results[TEST_RANK]);
}
//Takes an expression in a string and evalutates in, boolean or arithmentic
double evaluate_expression(string& input)
{
	SyntaxChecker check; //Here's our checker object
	double rhs, lhs, result; //Some doubles we will need
	syntax_status oper; //this is for passing into the function process
	stack<double> operands; //Operand stack
	stack<syntax_status> operators; //Operator stack
	list<exprToken> expression; //Here's the list we need to pass into syntax_check

	//Here we pass in the expression to see if it passes the test
	if (check.syntax_check(input, expression) != 0) //this also populates the list of tokens
	{
		return numeric_limits<double>::quiet_NaN(); //if the input is invalid, return NaN
	}
	if (expression.size() == 0)
	{
		return numeric_limits<double>::quiet_NaN();
	}

	//Iterate through the list of tokens
	for (list<exprToken>::iterator itr = expression.begin(); itr != expression.end(); ++itr)
	{
		//If it's a number push it on the operand stack
		if (itr->isANumber)
		{
			operands.push(itr->number);
			//If there is a negative or not on top of the stack, process it now
			while (!operators.empty() && isUnary(operators.top()))
			{
				if (isNot(operators.top()))
					result = !operands.top();
				else if (isNegative(operators.top()))
					result = -operands.top();
				operands.pop();
				operators.pop();
				operands.push(result);
			}
		}
		//If it's an operator
		else if (isOperator(itr->token))
		{
			//if there are none, push it onto the stack
			if (operators.empty())
			{
				operators.push(itr->token);
			}
			//if it's precedence is lower or equal to what's on top, process the last one
			else if (precedence(itr->token) <= precedence(operators.top()))
			{
				rhs = operands.top();
				operands.pop();
				lhs = operands.top();
				operands.pop();
				oper = operators.top();
				operators.pop();
				result = process(lhs, rhs, oper);
				operands.push(result);
				operators.push(itr->token);
			}
			//if it's of higher precedence, push it on to be processed later
			else if (precedence(itr->token) > precedence(operators.top()))
			{
				operators.push(itr->token);
			}
		}
		//it's an opening parenthesis, put it in operator stack
		else if (isOpen(itr->token))
		{
			operators.push(itr->token);
		}
		//It's a closing parenthesis, process until the last opening parenthesis
		else if (isClose(itr->token))
		{
			while (!isOpen(operators.top()))
			{
				rhs = operands.top();
				operands.pop();
				lhs = operands.top();
				operands.pop();
				oper = operators.top();
				operators.pop();
				operands.push(process(lhs, rhs, oper));
			}
			operators.pop(); //dump the last opening parenthesis, we're done with it
			
			//Now if there is a ! or - on top of the operator stack we need to evaluate it
			//for the expression that was inside the parenthesis
			while (!operators.empty() && isUnary(operators.top()))
			{
				if (isNot(operators.top()))
					result = !operands.top();
				else if (isNegative(operators.top()))
					result = -operands.top();
				operands.pop();
				operators.pop();
				operands.push(result);
			}
		}
		//If we have a - or ! we need to put it in the operand stack regardless of any precedence
		else if (isUnary(itr->token))
		{
			operators.push(itr->token);
		}

	}
	//After we finish going through the list, we need to evaluate any remaining operators
	while (!operators.empty())
	{
		rhs = operands.top();
		operands.pop();
		lhs = operands.top();
		operands.pop();
		oper = operators.top();
		operators.pop();
		operands.push(process(lhs, rhs, oper));
	}
	//The top of the operand stack is the solution
	return operands.top();


}
//This covers both isNegative and isNot
bool isUnary(syntax_status token) {
	return isNot(token) || isNegative(token);
}
Пример #30
0
 virtual State getState() const { return isNegative()? NEG_NUM : NUM; }