Ejemplo n.º 1
0
int main()
{
	int i,maxi,maxv,val;
	int r,g,b;
	for(i=0;i<16;i++)
	{
		scanf("%d%d%d",&rec[i].r,&rec[i].g,&rec[i].b);
	}
	while(scanf("%d%d%d",&r,&g,&b),r+1)
	{
		maxi=0;
		maxv=SUM(rec[0].r-r,rec[0].g-g,rec[0].b-b);
		for(i=1;i<16;i++)
		{
			val=SUM(rec[i].r-r,rec[i].g-g,rec[i].b-b);
			if(maxv>val)
			{
				maxi=i;
				maxv=val;
			}
		}
		printf("(%d,%d,%d) maps to (%d,%d,%d)\n",r,g,b,rec[maxi].r,rec[maxi].g,rec[maxi].b);
	}
	return 0;
}
Ejemplo n.º 2
0
int main()
{
	scanf("%d%d%d",&N,&C,&Q);
	int mi,ni,ai;
	for(int i=1;i<=C;i++)
	{
		
		scanf("%d%d%d",&mi,&ni,&ai);
		
		questy(b,mi,ai);
		questy(b,ni+1,-ai);
		
		questy(bi,mi,mi*ai);
		questy(bi,ni+1,-1*(ni+1)*ai);
	}
	
	int sum_a , sum_b; 
	for(int i=1;i<=Q;i++)
	{
		scanf("%d%d",&mi,&ni);
		//segma(org[i]) + (x+1)*segma(delta[i]) -segma(delta[i]*i),1 <= i <= x  
		//因为A为空,所以orj[i] ==0 
		sum_a=0+(ni+1)*SUM(b,ni)-SUM(bi,ni);
		sum_b=0+mi*SUM(b,mi-1)-SUM(bi,mi-1);
		printf("%d\n",sum_a-sum_b);
		
	}
	return 0;
}
Ejemplo n.º 3
0
int main(){
   int a=3, b=5;
   printf("a=%d, b = %d\n",a,b);
   printf("SQUARE(a) = %d\n",SQUARE(a));
   printf("SUM(a,9) = %d\n",SUM(a,9));
   printf("SUM(a,b) * SUM(a,b) = %d\n",
		SUM(a,b)*SUM(a,b));
   printf("SQUARE(a+b) = %d\n",SQUARE(a+b));

   return 0;
}
Ejemplo n.º 4
0
int hint_corner(SPFELD *psf)
{
  int sum=0;
  SFPOS *p=psf->p;

  SUM(A1,B1,A2,B2);
  SUM(H1,G1,H2,G2);
  SUM(A8,A7,B8,B7);
  SUM(H8,H7,G8,G7);

  return sum;
}
Ejemplo n.º 5
0
/* Уничтожение буфера. Функция вызывается только из внутренних задач.*/
static void combuf_destroy(const combuf_t combuf)
{
    ASSERT1(CHECK_COMBUF(combuf), "invalid combuf = %u", combuf);

    /* Пометить буфер для удаления */
    DESTROY(combuf);

    /* Если буфер последний в очереди, то удаляем его и
     * следующие буферы в очереди ( если они помечены для удаления ) */
    if (IS_BACK(combuf)) {
        cb_store_t _busy;
        cb_store_t cb_size;

        do {
            cb_size = SIZE(back);
            back = SUM(back, cb_size);

            __critical_enter();
            busy -= cb_size;
            _busy = busy;
            __critical_exit();

        } while ((0 < _busy) && IS_DESTROYED(back));

    }
}
Ejemplo n.º 6
0
/* функция поиска буфера по полю контроля буфера.
 * Функция вызывается только из задач данного модуля. */
static combuf_t combuf_search(const uint8_t mask, const uint8_t value)
{
    cb_store_t cb_size;
    cb_offset_t _front;
    uint8_t cb_ctrl;
    combuf_t cb_iter = back;


    while (cb_iter != front) {

        /* не защищаем CONTROL( cb_iter ), так как предполагаем,
         * что вычитывание атомарно */
        if (value == (CONTROL(cb_iter) & mask))
            return cb_iter;

        /* поле SIZE( cb_iter ) можно не вычитывать в крит. секции, так как
         * это поле не изменяется никем. Изменяется только в combuf_create, но
         * это не страшно:
         * 1. если combuf_create выз. из задачи, то всё хорошо. 
         *      front и поле size будут согласованы.
         * 2. если из прерывания, то тоже согласованы.  */
        cb_iter = SUM(cb_iter, SIZE(cb_iter));
    }

    return ENOTFOUND;
}
Ejemplo n.º 7
0
int main(int argc, char const *argv[])
{
  int x,y;
  scanf("%d %d",&x,&y);
  printf("%s%d\n","sum = ",SUM(x,y) );
  return 0;
}
Ejemplo n.º 8
0
combuf_t combuf_create(const uint8_t control, const combuf_size_t payload_size)
{
    const cb_store_t cb_size =
        COMBUF_HEAD_SIZE + payload_size + COMBUF_END_SIZE;
    cb_store_t _busy = cb_size;
    result_t res = ENOERR;
    cb_offset_t _front;

    /* критическая секция нужна, потому что combuf_create может быть
     * вызвана как из прерывания, так и из задачи. */
    __critical_enter();
    _busy += busy;
    if (_busy <= COMBUF_STORE_SIZE) {
        _front = front;
        front = SUM(front, cb_size);
        busy = _busy;
    } else
        res = ENOMEM;
    __critical_exit();

    if (ENOERR != res)
        return res;

    /* Можно не вносить в критическую секцию, поскольку доступ к этим
     * полям осуществляется пользователем по описателю буфера, который
     * ему ещё не возвращён. */
    BEGIN(_front) = BEGIN_MARKER;
    SIZE(_front) = cb_size;
    CONTROL(_front) = control | CREATE_MASK;

    return (combuf_t) _front;
}
Ejemplo n.º 9
0
/****************************************************************************
**
*F  SCTableProduct( <table>, <list1>, <list2> ) . product wrt structure table
**
**  'SCTableProduct'  returns the product   of  the two elements <list1>  and
**  <list2> with respect to the structure constants table <table>.
*/
void SCTableProdAdd (
    Obj                 res,
    Obj                 coeff,
    Obj                 basis_coeffs,
    Int                 dim )
{
    Obj                 basis;
    Obj                 coeffs;
    Int                 len;
    Obj                 k;
    Obj                 c1, c2;
    Int                 l;

    basis  = ELM_LIST( basis_coeffs, 1 );
    coeffs = ELM_LIST( basis_coeffs, 2 );
    len = LEN_LIST( basis );
    if ( LEN_LIST( coeffs ) != len ) {
        ErrorQuit("SCTableProduct: corrupted <table>",0L,0L);
    }
    for ( l = 1; l <= len; l++ ) {
        k = ELM_LIST( basis, l );
        if ( ! IS_INTOBJ(k) || INT_INTOBJ(k) <= 0 || dim < INT_INTOBJ(k) ) {
            ErrorQuit("SCTableProduct: corrupted <table>",0L,0L);
        }
        c1 = ELM_LIST( coeffs, l );
        c1 = PROD( coeff, c1 );
        c2 = ELM_PLIST( res, INT_INTOBJ(k) );
        c2 = SUM( c2, c1 );
        SET_ELM_PLIST( res, INT_INTOBJ(k), c2 );
        CHANGED_BAG( res );
    }
}
Ejemplo n.º 10
0
Archivo: ariths.c Proyecto: embray/gap
/****************************************************************************
**
*F  FuncSUM( <self>, <opL>, <opR> ) . . . . . . . . . . . . . . .  call 'SUM'
*/
Obj FuncSUM (
    Obj                 self,
    Obj                 opL,
    Obj                 opR )
{
    return SUM( opL, opR );
}
Ejemplo n.º 11
0
// Set min height and width of Boxes
void Boxer(Node* tree, int n) {
  if(GETN(tree, n).cutline == '-') {
    return;
  }
  Boxer(tree, GETN(tree, n).left);
  Boxer(tree, GETN(tree, n).right);
  if(GETN(tree, n).cutline == 'V') {
    GETN(tree, n).width = SUM(RIGHTC(tree, n).width, LEFTC(tree, n).width);
    GETN(tree, n).height = MAX(RIGHTC(tree, n).height, LEFTC(tree, n).height);
  }
  else {
    GETN(tree, n).height = SUM(RIGHTC(tree, n).height, LEFTC(tree, n).height);
    GETN(tree, n).width = MAX(RIGHTC(tree, n).width, LEFTC(tree, n).width);
  }
  return;
}
Ejemplo n.º 12
0
void PLEN2::AccelerationGyroSensor::sampling()
{
	#if _DEBUG
		system.outputSerial().println(F("=== running in function : AccelerationGyroSensor::sampling()"));
	#endif

	/*!
		@note
		Pin::RS485_TXD()をHIGHにすることで、データの流れを"サーボ基盤"→"頭基板"と変更する。
		頭基板のシリアルに任意のデータを送ると、2byte, ビッグエンディアンのバイト列で
		各センサ値を返却してくる。

		これを受信するために、データの流れを即座に"頭基板"→"サーボ基盤"と変更する必要がある。
	*/
	digitalWrite(Pin::RS485_TXD(), HIGH);
	system.BLESerial().write('<');
	system.BLESerial().flush();

	digitalWrite(Pin::RS485_TXD(), LOW);
	char  read_count = 0;
	char* filler = (char*)m_values;

	while (true)
	{
		if (system.BLESerial().available())
		{
			filler[read_count++] = system.BLESerial().read();
		}

		if (read_count == (SUM() * sizeof(int)))
		{
			// @attention '\n'の読み飛ばしのために必須
			system.BLESerial().read();

			for (int index = 0; index < SUM(); index++)
			{
				endianCast(m_values[index]);
			}

			break;
		}

		delay(1); // @attention 最適化対策と割り込みの疑似均等割り付けのために必須
	}
}
Ejemplo n.º 13
0
Archivo: ariths.c Proyecto: embray/gap
/****************************************************************************
**
*F  DiffDefault( <opL>, <opR> ) . . . . . . . . . . . . call 'SUM' and 'AINV'
*/
Obj DiffDefault (
    Obj                 opL,
    Obj                 opR )
{
    Obj                 tmp;

    tmp = AINV( opR );
    return SUM( opL, tmp );
}
Ejemplo n.º 14
0
// post order
// This is a minor version of Boxer function used for packing 
void MiniBoxer(Node* tree, int child, int parent) { 
  if(GETN(tree, child).cutline == 'V') {
    GETN(tree, child).width = SUM(RIGHTC(tree, child).width, LEFTC(tree, child).width);
    GETN(tree, child).height = MAX(RIGHTC(tree, child).height, LEFTC(tree, child).height);
  }
  else {
    GETN(tree, child).height = SUM(RIGHTC(tree, child).height, LEFTC(tree, child).height);
    GETN(tree, child).width = MAX(RIGHTC(tree, child).width, LEFTC(tree, child).width);
  }

  if(GETN(tree, parent).cutline == 'V') {
    GETN(tree, parent).width = SUM(RIGHTC(tree, parent).width, LEFTC(tree, parent).width);
    GETN(tree, parent).height = MAX(RIGHTC(tree, parent).height, LEFTC(tree, parent).height);
  }
  else {
    GETN(tree, parent).height = SUM(RIGHTC(tree, parent).height, LEFTC(tree, parent).height);
    GETN(tree, parent).width = MAX(RIGHTC(tree, parent).width, LEFTC(tree, parent).width);
  }
}
Ejemplo n.º 15
0
int main(void)
{

    int x = 5;
    int y = 8;

    printf("Sum of x and y is %d\n", SUM(x, y));

    return 0;
}
Ejemplo n.º 16
0
int main()
{
int res = 0;
char d,e;
res=fun(IN,OUT);
printf("the sum is:%d\n",res);
printf("...\n");
printf("my string is:%s\n",MYSTRING);
printf("sum is:%d\n",SUM(20,30));
}
Ejemplo n.º 17
0
int cal(struct exp * e)
{
	int val;
	switch (e->ex)
	{
		case '+': val = SUM(e->x, e->y); break;
		case '*': val = MUL(e->x, e->y); break;
		default : val  = 0; break;
	}

	return val;
}
Ejemplo n.º 18
0
/****************************************************************************
**
*F  SumFFEVecFFE(<elmL>,<vecR>) . . . .  sum of an fin field elm and a vector
**
**  'SumFFEVecFFE' returns the sum of the fin field elm <elmL> and the vector
**  <vecR>.  The sum is a  list, where each element is  the sum of <elmL> and
**  the corresponding element of <vecR>.
**
**  'SumFFEVecFFE' is an improved version  of  'SumSclList', which  does  not
**  call 'SUM'.
*/
Obj             SumFFEVecFFE (
    Obj                 elmL,
    Obj                 vecR )
{
    Obj                 vecS;           /* handle of the sum               */
    Obj *               ptrS;           /* pointer into the sum            */
    FFV                 valS;           /* the value of a sum              */
    Obj *               ptrR;           /* pointer into the right operand  */
    FFV                 valR;           /* the value of an element in vecR */
    UInt                len;            /* length                          */
    UInt                i;              /* loop variable                   */
    FF                  fld;            /* finite field                    */
    FF *                succ;           /* successor table                 */
    FFV                 valL;           /* the value of elmL               */

    /* get the field and check that elmL and vecR have the same field      */
    fld = FLD_FFE(ELM_PLIST(vecR, 1));
    if (FLD_FFE(elmL) != fld) {
        /* check the characteristic                                          */
        if (CHAR_FF(fld) == CHAR_FF(FLD_FFE(elmL)))
            return SumSclList(elmL, vecR);

        elmL = ErrorReturnObj(
            "<elm>+<vec>: <elm> and <vec> must belong to the same finite field",
            0L, 0L, "you can replace <elm> via 'return <elm>;'");
        return SUM(elmL, vecR);
    }

    /* make the result list                                                */
    len = LEN_PLIST(vecR);
    vecS = NEW_PLIST(IS_MUTABLE_OBJ(vecR) ?
                T_PLIST_FFE : T_PLIST_FFE + IMMUTABLE, len);
    SET_LEN_PLIST(vecS, len);

    /* to add we need the successor table                                  */
    succ = SUCC_FF(fld);

    /* loop over the elements and add                                      */
    valL = VAL_FFE(elmL);
    ptrR = ADDR_OBJ(vecR);
    ptrS = ADDR_OBJ(vecS);
    for (i = 1; i <= len; i++) {
        valR = VAL_FFE(ptrR[i]);
        valS = SUM_FFV(valL, valR, succ);
        ptrS[i] = NEW_FFE(fld, valS);
    }

    /* return the result                                                   */
    return vecS;
}
Ejemplo n.º 19
0
int main()
{
	int x = -6;
	int y = -9;

	int s = SUM(x,y);
	//int s = SUM(x,y)*10;  //如果还按之前的写法就有二义性,并且还是错的。
	int abs = SUB_ABS(++x, y);

	printf("x+y的值为:%d\n", s);
	printf("++x和y之差的绝对值为:%d\n", abs);

	system("pause");
	return 0;
}
Ejemplo n.º 20
0
int main(int argc, char **argv) {

#define N1 100
    int i,sum = 0;
    struct stu s;
    int inc;
    union Union u;
    u.a= 1;
    u.c = ' ';
    struct st s1;
    s1.b =0;
    s1.d = 'c';
    Node no;
    no.a=1;
    no.ch='a';
    swap(&s1,&no);
    int jj = 1;
    sum++;
    for(inc = 0; inc < N1; inc++) {
        int y=s.a;
        int j;
        for(j = 0; j < N; j++) {
            j += 2;
        }
	//s1.b++;
        sum += jj;
        sum += argc;
        //no.a++;
        printf(" \"sum = %d\n", sum);
    }/*This is
a test*/

for(i = 0 ; i<100;i++)
 SUM(sum);

    return sum;
#undef N1
}
Ejemplo n.º 21
0
/****************************************************************************
**
*F  SumVecFFEVecFFE(<vecL>,<vecR>)  . . . . . . . . . . .  sum of two vectors
**
**  'SumVecFFEVecFFE' returns the sum  of the two  vectors <vecL> and <vecR>.
**  The sum is a new list, where each element is the sum of the corresponding
**  elements of <vecL> and <vecR>.
**
**  'SumVecFFEVecFFE' is an improved version of 'SumListList', which does not
**  call 'SUM'.
*/
Obj             SumVecFFEVecFFE (
    Obj                 vecL,
    Obj                 vecR )
{
    Obj                 vecS;           /* handle of the sum               */
    Obj *               ptrS;           /* pointer into the sum            */
    FFV                 valS;           /* one element of sum list         */
    Obj *               ptrL;           /* pointer into the left operand   */
    FFV                 valL;           /* one element of left operand     */
    Obj *               ptrR;           /* pointer into the right operand  */
    FFV                 valR;           /* one element of right operand    */
    UInt                lenL, lenR, len; /* length                          */
    UInt                lenmin;
    UInt                i;              /* loop variable                   */
    FF                  fld;            /* finite field                    */
    FF *                succ;           /* successor table                 */

    /* check the lengths                                                   */
    lenL = LEN_PLIST(vecL);
    lenR = LEN_PLIST(vecR);
    if (lenR > lenL) {
        len = lenR;
        lenmin = lenL;
    } else {
        len = lenL;
        lenmin = lenR;
    }

    /* check the fields                                                    */
    fld = FLD_FFE(ELM_PLIST(vecL, 1));
    if (FLD_FFE(ELM_PLIST(vecR, 1)) != fld) {
        /* check the characteristic                                        */
        if (CHAR_FF(fld) == CHAR_FF(FLD_FFE(ELM_PLIST(vecR, 1))))
            return SumListList(vecL, vecR);

        vecR = ErrorReturnObj(
            "Vector +: vectors have different fields",
            0L, 0L, "you can replace vector <right> via 'return <right>;'");
        return SUM(vecL, vecR);
    }

    /* make the result list                                                */
    vecS = NEW_PLIST((IS_MUTABLE_OBJ(vecL) || IS_MUTABLE_OBJ(vecR)) ?
                T_PLIST_FFE : T_PLIST_FFE + IMMUTABLE, len);
    SET_LEN_PLIST(vecS, len);

    /* to add we need the successor table                                  */
    succ = SUCC_FF(fld);

    /* loop over the elements and add                                      */
    ptrL = ADDR_OBJ(vecL);
    ptrR = ADDR_OBJ(vecR);
    ptrS = ADDR_OBJ(vecS);
    for (i = 1; i <= lenmin; i++) {
        valL = VAL_FFE(ptrL[i]);
        valR = VAL_FFE(ptrR[i]);
        valS = SUM_FFV(valL, valR, succ);
        ptrS[i] = NEW_FFE(fld, valS);
    }
    if (lenL < lenR)
        for (; i <= len; i++)
            ptrS[i] = ptrR[i];
    else
        for (; i <= len; i++)
            ptrS[i] = ptrL[i];

    /* return the result                                                   */
    return vecS;
}
Ejemplo n.º 22
0
void digit (int a) {
  if (a<10)
    putchar (SUM (a,48));
  if (9<a)
    putchar (SUM (a,55));
}
Ejemplo n.º 23
0
Obj SCTableProductHandler (
    Obj                 self,
    Obj                 table,
    Obj                 list1,
    Obj                 list2 )
{
    Obj                 res;            /* result list                     */
    Obj                 row;            /* one row of sc table             */
    Obj                 zero;           /* zero from sc table              */
    Obj                 ai, aj;         /* elements from list1             */
    Obj                 bi, bj;         /* elements from list2             */
    Obj                 c, c1, c2;      /* products of above               */
    Int                 dim;            /* dimension of vectorspace        */
    Int                 i, j;           /* loop variables                  */

    /* check the arguments a bit                                           */
    if ( ! IS_SMALL_LIST(table) ) {
        table = ErrorReturnObj(
            "SCTableProduct: <table> must be a list (not a %s)",
            (Int)TNAM_OBJ(table), 0L,
            "you can replace <table> via 'return <table>;'" );
        return SCTableProductHandler( self, table, list1, list2 );
    }
    dim = LEN_LIST(table) - 2;
    if ( dim <= 0 ) {
        table = ErrorReturnObj(
            "SCTableProduct: <table> must be a list with at least 3 elements",
            0L, 0L,
            "you can replace <table> via 'return <table>;'" );
        return SCTableProductHandler( self, table, list1, list2 );
    }
    zero = ELM_LIST( table, dim+2 );
    if ( ! IS_SMALL_LIST(list1) || LEN_LIST(list1) != dim ) {
        list1 = ErrorReturnObj(
            "SCTableProduct: <list1> must be a list with %d elements",
            dim, 0L,
            "you can replace <list1> via 'return <list1>;'" );
        return SCTableProductHandler( self, table, list1, list2 );
    }
    if ( ! IS_SMALL_LIST(list2) || LEN_LIST(list2) != dim ) {
        list2 = ErrorReturnObj(
            "SCTableProduct: <list2> must be a list with %d elements",
            dim, 0L,
            "you can replace <list2> via 'return <list2>;'" );
        return SCTableProductHandler( self, table, list1, list2 );
    }

    /* make the result list                                                */
    res = NEW_PLIST( T_PLIST, dim );
    SET_LEN_PLIST( res, dim );
    for ( i = 1; i <= dim; i++ ) {
        SET_ELM_PLIST( res, i, zero );
    }
    CHANGED_BAG( res );

    /* general case                                                        */
    if      ( EQ( ELM_LIST( table, dim+1 ), INTOBJ_INT(0) ) ) {
        for ( i = 1; i <= dim; i++ ) {
            ai = ELM_LIST( list1, i );
            if ( EQ( ai, zero ) )  continue;
            row = ELM_LIST( table, i );
            for ( j = 1; j <= dim; j++ ) {
                bj = ELM_LIST( list2, j );
                if ( EQ( bj, zero ) )  continue;
                c = PROD( ai, bj );
                if ( ! EQ( c, zero ) ) {
                    SCTableProdAdd( res, c, ELM_LIST( row, j ), dim );
                }
            }
        }
    }

    /* commutative case                                                    */
    else if ( EQ( ELM_LIST( table, dim+1 ), INTOBJ_INT(1) ) ) {
        for ( i = 1; i <= dim; i++ ) {
            ai = ELM_LIST( list1, i );
            bi = ELM_LIST( list2, i );
            if ( EQ( ai, zero ) && EQ( bi, zero ) )  continue;
            row = ELM_LIST( table, i );
            c = PROD( ai, bi );
            if ( ! EQ( c, zero ) ) {
                SCTableProdAdd( res, c, ELM_LIST( row, i ), dim );
            }
            for ( j = i+1; j <= dim; j++ ) {
                bj = ELM_LIST( list2, j );
                aj = ELM_LIST( list1, j );
                if ( EQ( aj, zero ) && EQ( bj, zero ) )  continue;
                c1 = PROD( ai, bj );
                c2 = PROD( aj, bi );
                c = SUM( c1, c2 );
                if ( ! EQ( c, zero ) ) {
                    SCTableProdAdd( res, c, ELM_LIST( row, j ), dim );
                }
            }
        }
    }

    /* anticommutative case                                                */
    else if ( EQ( ELM_LIST( table, dim+1 ), INTOBJ_INT(-1) ) ) {
        for ( i = 1; i <= dim; i++ ) {
            ai = ELM_LIST( list1, i );
            bi = ELM_LIST( list2, i );
            if ( EQ( ai, zero ) && EQ( bi, zero ) )  continue;
            row = ELM_LIST( table, i );
            for ( j = i+1; j <= dim; j++ ) {
                bj = ELM_LIST( list2, j );
                aj = ELM_LIST( list1, j ); 
                if ( EQ( aj, zero ) && EQ( bj, zero ) )  continue;
                c1 = PROD( ai, bj );
                c2 = PROD( aj, bi );
                c = DIFF( c1, c2 );
                if ( ! EQ( c, zero ) ) {
                    SCTableProdAdd( res, c, ELM_LIST( row, j ), dim );
                }
            }
        }
    }

    /* return the result                                                   */
    return res;
}
Ejemplo n.º 24
0
int main()
{
    SUM(1,2);
    return 0;
}
Ejemplo n.º 25
0
Archivo: test.c Proyecto: ynadji/lisp
int main(int argc, char **argv)
{
	printf("SUM(3,4) == %d\n", SUM(3,4));

	return 0;
}
Ejemplo n.º 26
0
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
void Calculate_Baseline( std::vector<double> DIAM,std::vector<double> ARC, std::vector<double> &baseline, std::vector<double> &weights ){
    baseline.clear();
    weights.clear();


    unsigned int Npoints = ARC.size();
    baseline.resize(Npoints, 0.0);
    weights.resize(Npoints, 0.0);
    std::vector<double> r_mad (Npoints, 0.0);
    std::vector<double> DIAM_noise (Npoints, 0.0);

    double MIN_, MAX_;

    //REMOVE OUTLIERS USING MAD (Median Absolute Deviation)
    double outlier_cutoff = 3.0;
    double median_D, mad;

    median_D = MEDIAN(DIAM);
    for(unsigned i = 0; i < Npoints; i = i + 1) {
        r_mad[i] = abs( DIAM[i] - median_D );
    }
    mad = MEDIAN(r_mad);

    // use fitting weights to exclude the outliers
    if( mad > 1.0e-6 ) {
        for(unsigned i = 0; i < Npoints; i = i + 1 ) {
            r_mad[i] = abs( DIAM[i] - median_D ) / mad;
            if( r_mad[i] > outlier_cutoff ) {
                weights[i] = 0.0;
            } else {
                weights[i] = 1.0;
            }
        }
    } else {
        // will end up here if more than 50% of data points had the same value
        // add 1% noise to DIAM profile and recalculate mad
        std::vector<double> DIAM_noise = DIAM;
        MIN_ = MINIMUM(DIAM);
        for (unsigned i=0; i < Npoints; i = i + 1 ) {
            DIAM_noise[i] = DIAM[i] * 0.01 * MIN_ * RandGen((double)-1.0,(double)1.0);
        }
        median_D = MEDIAN(DIAM_noise);
        for(unsigned i = 0; i < Npoints; i = i + 1) {
            r_mad[i] = abs( DIAM_noise[i] - median_D );
        }
        mad = MEDIAN(r_mad);

        if( mad > 1.0e-6 ) {
            for(unsigned i = 0; i < Npoints; i = i + 1 ) {
                r_mad[i] = abs( DIAM_noise[i] - median_D ) / mad;
                if( r_mad[i] > outlier_cutoff ) {
                    weights[i] = 0.0;
                } else {
                    weights[i] = 1.0;
                }
            }
        }else{
            //this is tricky situation; try signalling outliers assuming Normal dist...
            double s = STDEV(DIAM);
            median_D = MEDIAN(DIAM);
            for(unsigned i = 0; i < Npoints; i = i + 1 ) {
                if( abs( DIAM[i] - median_D ) > 2.0 * s ) {
                    weights[i] = 0.0;
                } else {
                    weights[i] = 1.0;
                }
            }
        }
    }


    //PERFORM 2ND ORDER POLYNOMIAL FIT
    double a, b, c;
    std::vector<double> temp_mad;

    double w1 = 0.0;
    double wx = 0.0, wx2 = 0.0, wx3 = 0.0, wx4 = 0.0;
    double wy = 0.0, wyx = 0.0, wyx2 = 0.0;
    double tmpx = 0.0, tmpy = 0.0;
    double den;
    double x, y, w;

    if(DIAM.size()-SUM(weights)>2){
        for(unsigned i = 0; i < Npoints; i = i + 1 ) {
            x = ARC[i];
            y = DIAM[i];
            w = weights[i];
            w1 += w;
            tmpx = w * x;
            wx += tmpx;
            tmpx *= x;
            wx2 += tmpx;
            tmpx *= x;
            wx3 += tmpx;
            tmpx *= x;
            wx4 += tmpx;
            tmpy = w * y;
            wy += tmpy;
            tmpy *= x;
            wyx += tmpy;
            tmpy *= x;
            wyx2 += tmpy;
        }

        den = wx2 * wx2 * wx2 - 2.0 * wx3 * wx2 * wx + wx4 * wx * wx + wx3 * wx3 * w1 - wx4 * wx2 * w1;
        if( den == 0.0 ) {
            a = 0.0;
            b = 0.0;
            c = 0.0;
        } else {
            a = (wx * wx * wyx2 - wx2 * w1 * wyx2 - wx2 * wx * wyx + wx3 * w1 * wyx + wx2 * wx2 * wy - wx3 * wx * wy) / den;
            b = (-wx2 * wx * wyx2 + wx3 * w1 * wyx2 + wx2 * wx2 * wyx - wx4 * w1 * wyx - wx3 * wx2 * wy + wx4 * wx * wy) / den;
            c = (wx2 * wx2 * wyx2 - wx3 * wx * wyx2 - wx3 * wx2 * wyx + wx4 * wx * wyx + wx3 * wx3 * wy - wx4 * wx2 * wy) / den;
        }
        // FILL IN DATA
        double d;
        for(unsigned i = 0; i < Npoints; i = i + 1 ) {
            x = ARC[i];
            d = a * x * x + b * x + c;
            if( d > 1.0e-6 ) {
                baseline[i] = d;
            } else {
                baseline[i] = 1.0e-6;
            }
        }
    }else{
        median_D = MEDIAN(DIAM);
        for(unsigned i = 0; i < Npoints; i = i + 1 ) {
            baseline[i] = median_D;
        }
    }
    // Do not allow the baseline to go bellow the minimal diameter, or above maximal diameter - truncate
    MIN_ = MINIMUM(DIAM);
    MAX_ = MAXIMUM(DIAM);
    for(unsigned i = 0; i < Npoints; i = i + 1 ) {
        if (baseline[i]<MIN_){
            baseline[i] = MIN_;
        }
        if (baseline[i]>MAX_){
            baseline[i] = MAX_;
        }
    }
    return;
}
Ejemplo n.º 27
0
Obj GAP_SUM(Obj a, Obj b)
{
    return SUM(a, b);
}
Ejemplo n.º 28
0
Archivo: define2.c Proyecto: kenu/okc
int main7()
{
 int a = 10, b = 20;
 
 printf("%d\n", SUM(a, b));
}
Ejemplo n.º 29
0
double ppf_sum_callback(double x, double y)
{
	return(SUM(x,y));
}
Ejemplo n.º 30
0
int main(void) {

    /*
    # Comments are replaced by spaces.
    */
    {
        int/* */a = 1;
        assert(a == 1);
    }

    /*
    # Newline in macro

    # Multiline macro

        Impossible:

        - http://stackoverflow.com/questions/10419530/multi-line-preprocessor-macros
        - http://stackoverflow.com/questions/98944/how-to-generate-a-newline-in-a-cpp-macro
    */

    /*
    # #define

        You can put preprocessor directives anywhere
        but putting on global scope is the more standard and simple approach

        Use defines with discretion: they make it much harder to debug!
    */
    {

        /*
        Syntax: the line must start with `#`,
        but there can be spaces after it to give indentation.
        */
        {
#define SPACE_AFTER_HASH 1
            assert(SPACE_AFTER_HASH == 1);
        }

        /*
        # Constants

            Use sparingly.

            - constants have scope
            - produce meaningful error messages
        */
        {
            {
#define CTE 1
                assert(CTE == 1);
            }

            /*
            Don't forget to protect arithmetic operations
            or associativity may get you.
            */
            {
                /* Use parenthesis or order of operation might destroy you: */
#define PROTECT_FAIL 1 + 1
                assert(PROTECT_FAIL * 2 == 3);
#define PROTECT (1 + 1)
                assert(PROTECT * 2 == 4);
            }

            /*
            Expansion is lazy: macros do not expand in `#define`
            but only when the macro is used.
            */
            {
#define LAZY0 LAZY1
#define LAZY1 LAZY2
#define LAZY2 2
                assert(LAZY2 == 2);
            }
        }

        /* # Redefine macros */
        {
            /* Cannot redefine macros directly. */
            {
#define REDEFINE_FAIL 1
                /* ERROR */
                /*#define REDEFINE_FAIL 2*/
            }

            /* Must first undef. */
            {
#define REDEFINE 1
#undef REDEFINE
#define REDEFINE 2
                assert(REDEFINE == 2);
            }
        }

        /* # Functions (preprocessor) */
        {
            /*
            Generates:

                assert(1 + 1 == 2);

            Not:

                assert(2 == 2);
            */
            {
#define SUM(x, y) x + y
                assert(SUM(1, 1) == 2);
            }

            /*
            # Comma protection

                The macro engine has to do some kind of parsing to determine that
                the comma of the function (1) is not the comma of the macro (2).

                What it seems to do is simply check if the comma is between pairs of:

                - parenthesis
                - double quotes

                and if yes ignore it.

                This does not however cover C++ template parameters, and `assert` + template is a common break case
                http://stackoverflow.com/questions/4496842/pass-method-with-template-arguments-to-a-macro

                Pure C also has cases in which it is necessary to use parenthesis,
                for example when the comma operator is used.

                A more complicated case in which protecting parenthesis break:
                http://stackoverflow.com/questions/9187614/how-do-i-have-a-comma-inside-braces-inside-a-macro-argument-when-parentheses-cau
            */
            {
                assert(SUM(int_int_int_func(1, 1), 1) == 3);
                /*                           ^   ^ */
                /*                           1   2 */

                int i = 1;
                assert(SUM((i++, i), 1) == 3);
                /*                 ^ */
                /*                 comma operator */

                /* ERROR must protect the comma operator. */
                /*assert(SUM(i++, i, 1) == 3);*/

#define CAT(x, y) x y
                /* Strings are treated as a single token, so commas inside strings are fine. */
                assert(strcmp(CAT("1,", "2"), "1,2") == 0);
            }

            /*
            # Function inside argument

                - http://stackoverflow.com/questions/163365/how-do-i-make-a-c-macro-behave-like-a-function
                - http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros
            */
            {
                /* TODO */
            }

            /*
            # Argument inside string

            # #
            */
            {
                /* Strings are treated as single tokens, so arguments don't expand by default. */
#define ARG_IN_STRING_BAD(x) "x"
                assert(strcmp(ARG_IN_STRING_BAD("a"), "x") == 0);

                /*
                Solution: use # stringification.

                It simply adds "" around the argument and expands it.
                */
#define STRINGIFY(x) #x
                assert(strcmp(STRINGIFY(a), "a") == 0);
                assert(strcmp(STRINGIFY(""), "\"\"") == 0);
                /* ERROR: parsing fails because of unbalanced `"`. */
                /*assert(strcmp(STRINGIFY("), "\"") == 0);*/

#define STRINGIFY_CAT(x) "a" STRINGIFY(x) "c"
                assert(strcmp(STRINGIFY_CAT(b), "abc") == 0);

                /*
                This fails however for macro arguments, which don't expand when `# arg` is used!

                Solution Use a two step expansion process...

                - http://stackoverflow.com/questions/8283596/whats-the-difference-between-these-two-macros?lq=1
                - http://stackoverflow.com/questions/6742501/whats-the-exact-step-of-macro-expanding

                TODO what is the rationale for that exception of not expanding upon `#`?
                */
#define STRINGIFY_ARG a
                assert(strcmp(STRINGIFY(STRINGIFY_ARG), "STRINGIFY_ARG") == 0);
            }

            /* # variadic macro functions */
            {
                char s[4];
#define SPRINTF(string, format, ...) sprintf(string, format, __VA_ARGS__)
                SPRINTF(s, "%c%c", 'a', 'b');
                assert(strcmp(s, "ab") == 0);
            }

#if __STDC_VERSION__ >= 199901L
            /*
            # Empty macro arguments

                http://stackoverflow.com/questions/7666344/are-empty-macro-arguments-legal-in-c11
            */
            {
#define EMPTY(x) x ## 2 ==
                assert(EMPTY(1) 12);

                /*
                TODO if the argument is empty,
                does it still count for concatenation?
                */
                assert(EMPTY() 2);
            }
#endif
        }

        /*
        # #include

            It is possible, and very confusing, to include any type of file,
            not just header files.
        */
        {
            int i = 0;
#include "preprocessor.inc"
            assert(i == 1);
        }
    }

    /*
    # #undef

        Undo a previous define.
    */
    {
#define UNDEF_TEST 1
#undef UNDEF_TEST
#ifdef UNDEF_TEST
# error
#endif
    }

    /*
    # Concatenate

    # Double hash preprocessor operator

    # ##

        `##` allows to concatenate a preprocessor function arguments without spaces between them.
    */
    {
        /* Basic. */
        {
#define CAT_NO_SPACE(x) x ## d
            int CAT_NO_SPACE(c_) = 1;
            assert(c_d == 1);
        }

        /*
        Multiple concatenation insanity:
        http://stackoverflow.com/questions/1489932/c-preprocessor-and-concatenation
        */
        {
            {
#define CAT_FAIL_VAR 0
#define CAT_FAIL x ## CAT_FAIL_VAR
                int CAT_FAIL = 1;
                assert(xCAT_FAIL_VAR == 1);
            }

            /* Solution. */
            {
#define CAT_VAR 0
#define PASTER(x,y) x ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define CAT_OK EVALUATOR(x, CAT_VAR)
                int CAT_OK = 1;
                assert(x0 == 1);
            }
        }
    }

    /*
    # #ifdef

        Check if preprocessor variable is defined.

        # or and ifdef

            http://stackoverflow.com/questions/965700/c-preprocessor-testing-definedness-of-multiple-macros

            Almost the same as `#if defined()`,
            except you can use `#if defined()` with `|| on a single line as:

                #if defined(X) || defined(Y)

            while

                #ifdef(X) || ifdef(Y)
                #ifdef X || Y

            compiles but does not do what you expect:
            TODO legal?

            For `&&`, we could get away with:

                #ifdef(X)
                #ifdef(Y)

            but there is no alternative for `||`.

    # #ifndef

        Negation of ifdef.

    # #defined

        Like ifdef, but more flexible
        as you can use it inside `#if` with boolean operators.
    */
    {
#ifdef COMMANDLINE
        /* gcc -DCOMMANDLINE c.c */
        puts("C");
#else
        /* gcc c.c */
        puts("no C");
#endif
    }

    /*
    # #if

    # #else

    # #elif

        The preprocessor can do certain integer arithmetic operations such as: +, -, ==, <.
    */
    {
#if 1 == 0
# error
#elif 1 == 1
#else
# error
#endif

#define INIF 1
#if INIF + 1 == 2
#else
# error
#endif

#if 16 == 0x10
#else
# error
#endif

        /* Undefined evaluate equal. */
        {
#if NOT_DEFINED == NOT_DEFINED2
#else
# error
#endif
        }

        /*
        Cannot compare strings directly!
        http://stackoverflow.com/questions/2335888/how-to-compare-string-in-c-conditional-preprocessor-directives
        Always define to integers.
        */
#define STR1 1
#define STR2 2
#define STR STR1

#if STR == STR1
#elif STR == STR2
# error
#endif
    }

    /*
    # && preprocessor

    # and preprocessor
    */
#define C 1
#if defined(C) && C > 0
#else
# error
#endif

    /*
    # #error

        Print an error message to stderr and stop compilation.

        Useful to enforce preprocessor conditions.
    */
    {
        /* #error "the error message" */
    }

    /*
    # null directive

        A `#` followed by newline is ignored.
    */
    {
#
    }

    /*
    # #pragma

        C99 specifies that:

            # pragma X Y Z ...

        -   if `X != STDC`, does something implementation defined, and therefore not portable.

            Examples: `#pragma once`

        -   else, then the statement must take a form:

                # pragma STDC FP_CONTRACT on-off-switch
                # pragma STDC FENV_ACCESS on-off-switch
                # pragma STDC CX_LIMITED_RANGE on-off-switch

            all of which are portable.
    */

    /*
    # #line

        Set the line and optionally filename that is seen by `__FILE__` and `__LINE__`.
    */
    {
        /*#line 1*/
    }

    /*
    # Predefined preprocessor macros

    # Standard preprocessor defines

        Some preprocessor vars are automatically defined by certain compilers
        although they are not c standards. Those are not discussed here.

        List of standard defines: http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

        List all them on GCC:

            gcc -dM -E - < /dev/null | sort

        Sample output:

            #define _LP64 1
            #define _STDC_PREDEF_H 1
            #define __ATOMIC_ACQUIRE 2
            #define __ATOMIC_ACQ_REL 4
            #define __ATOMIC_CONSUME 1
            #define __ATOMIC_HLE_ACQUIRE 65536
            #define __ATOMIC_HLE_RELEASE 131072
            #define __ATOMIC_RELAXED 0
            #define __ATOMIC_RELEASE 3
            #define __ATOMIC_SEQ_CST 5
    */
    {
        /*
        # STDC_VERSION

        # __STDC_VERSION__

            String representing version of the c std lib. Format: yyyymm (base 10).

            Some values:

            - C11: 201112L
            - C99: 199901L

            http://sourceforge.net/p/predef/wiki/Standards/

            Apperas undefined in C99
        */
        {
            printf("__STDC_VERSION__ = %li\n", __STDC_VERSION__);
        }

        /*
        # __STDC__

        # STDC

            1 if the implementation is conforming, 0 otherwise.

            TODO check: on GCC, 1 with `-std=cXX`, 0 with `-std=gnuXX`.
        */
        {
            printf("__STDC__ = %d\n", __STDC__);
        }

        /*
        # __STDC_HOSTED__

        # STDC

            Indicate if the compilation is hosted or not.

        # Hosted

        # Freestanding

            Concept defined in ANSI C.

            Basically, a freestanding implementation does not need to provide an stdlib.

            In GCC, controlled by the `-ffreestainding` option.
        */
        {
            printf("__STDC_HOSTED__ = %d\n", __STDC_HOSTED__);
        }


        /*
        # __cplusplus

            Defined only if using C++ compiler.

            C99 says that C must not define it.
        */
#ifdef __cplusplus
        printf("__cplusplus\n");
#endif

        /*
        # __FILE__

            Absolute or relative path of current file.
        */
        {
            printf("__FILE__ = %s\n", __FILE__);
        }

        /*
        # __LINE__

            Current source code line.

            Useful for debugging.

            If in a `.h`, position inside the `.h` before inclusion.
        */
        {
            printf("__LINE__ = %d\n", __LINE__);
        }

        printf("__DATE__ = %s\n", __DATE__);

        printf("__TIME__ = %s\n", __TIME__);

#ifdef __WIN32__
        /* Automatically defined by certain compilers on windows: */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__WIN32__");
#endif

#ifdef _LIBC
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("_LIBC");
#endif

#ifdef __ILP32__
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__ILP32__");
#endif

#ifdef ___X32_SYSCALL_BIT
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("___X32_SYSCALL_BIT");
#endif

        /*
        # IEEE-754

            IEC 60559 has the same contents as the IEEE 754-2008,
            Outside of the C standard it is commonly known by the IEEE name, or simply as IEEE floating point.

            IEEE dates from 1985.

        # __STDC_IEC_559__

        # IEC 60599

            Standard on which floating point formats and operations should be available
            on an implementation, and how they should work.

            Good overview wiki article: <http://en.wikipedia.org/wiki/IEEE_floating_point>

            Many CUPs implement large parts of IEC 60599, which C implementations can use if available.

            The C standard specifies that implementing the IEC 60599 is not mandatory.

            If the macro `__STDC_IEC_559__` is defined this means that the implementation is compliant
            to the interface specified in Annex F of the C11 standard.

            C99 introduced many features which allow greater conformance to IEC 60599.
        */
        {
#ifdef __STDC_IEC_559__
            puts("__STDC_IEC_559__");

            /*
            I think it guaranteed by the standard on annex F:

            - The float type matches the IEC 60559 single format.
            - The double type matches the IEC 60559 double format.
            - The long double type matches an IEC 60559 extended format,307) else a
              non-IEC 60559 extended format, else the IEC 60559 double format.
            */
            assert(sizeof(float) == 4);
            assert(sizeof(double) == 8);
#endif
        }

        /*
        # Expand macro to another macro

            Nope:
            http://stackoverflow.com/questions/1262063/preprocessor-macro-expansion-to-another-preprocessor-directive
        */

#ifndef __STDC_NO_ATOMICS__
        /* Indicates no C11 support for `_Atomic` and `<stdatomic.h>`. */
        puts("__STDC_NO_ATOMICS__");
#else
#include <stdatomic.h>
        _Atomic int i;
#endif
    }

    return EXIT_SUCCESS;
}