void RenderMathMLFraction::layoutBlock(bool relayoutChildren, LayoutUnit)
{
    ASSERT(needsLayout());

    if (!relayoutChildren && simplifiedLayout())
        return;

    if (!isValid()) {
        setLogicalWidth(0);
        setLogicalHeight(0);
        clearNeedsLayout();
        return;
    }

    numerator().layoutIfNeeded();
    denominator().layoutIfNeeded();

    setLogicalWidth(std::max(numerator().logicalWidth(), denominator().logicalWidth()));

    updateLineThickness();
    LayoutUnit verticalOffset = 0; // This is the top of the renderer.
    LayoutPoint numeratorLocation(horizontalOffset(numerator(), element().numeratorAlignment()), verticalOffset);
    numerator().setLocation(numeratorLocation);

    LayoutUnit numeratorAscent = ascentForChild(numerator());
    LayoutUnit numeratorDescent = numerator().logicalHeight() - numeratorAscent;
    LayoutUnit denominatorAscent = ascentForChild(denominator());
    LayoutUnit denominatorDescent = denominator().logicalHeight() - denominatorAscent;
    if (isStack()) {
        LayoutUnit gapMin, topShiftUp, bottomShiftDown;
        getStackParameters(gapMin, topShiftUp, bottomShiftDown);
        LayoutUnit gap = topShiftUp - numeratorDescent + bottomShiftDown - denominatorAscent;
        if (gap < gapMin) {
            // If the gap is not large enough, we increase the shifts by the same value.
            LayoutUnit delta = (gapMin - gap) / 2;
            topShiftUp += delta;
            bottomShiftDown += delta;
        }
        verticalOffset += numeratorAscent + topShiftUp; // This is the middle of the stack gap.
        m_ascent = verticalOffset + mathAxisHeight();
        verticalOffset += bottomShiftDown - denominatorAscent;
    } else {
        LayoutUnit numeratorGapMin, denominatorGapMin, numeratorMinShiftUp, denominatorMinShiftDown;
        getFractionParameters(numeratorGapMin, denominatorGapMin, numeratorMinShiftUp, denominatorMinShiftDown);
        verticalOffset += std::max(numerator().logicalHeight() + numeratorGapMin + m_lineThickness / 2, numeratorAscent + numeratorMinShiftUp); // This is the middle of the fraction bar.
        m_ascent = verticalOffset + mathAxisHeight();
        verticalOffset += std::max(m_lineThickness / 2 + denominatorGapMin, denominatorMinShiftDown - denominatorAscent);
    }

    LayoutPoint denominatorLocation(horizontalOffset(denominator(), element().denominatorAlignment()), verticalOffset);
    denominator().setLocation(denominatorLocation);

    verticalOffset = std::max(verticalOffset + denominator().logicalHeight(), m_ascent + denominatorDescent); // This is the bottom of our renderer.
    setLogicalHeight(verticalOffset);

    clearNeedsLayout();
}
Exemplo n.º 2
0
void pb_util::normalize(unsigned num_args, rational const* coeffs, rational const& k) {
    rational d(1);
    for (unsigned i = 0; i < num_args; ++i) {
        d = lcm(d, denominator(coeffs[i]));
    }
    m_coeffs.reset();
    for (unsigned i = 0; i < num_args; ++i) {
        m_coeffs.push_back(d*coeffs[i]);
    }
    m_k = d*k;
}
Exemplo n.º 3
0
// returns string with numerator / denominator (e.g. "1/2")
const std::string Fraction::asString( void )
{
    std::stringstream outStream;
    
    if (isValid())
        outStream << numerator() << "/" << denominator();
    else
        outStream << "Nan";
    
    return std::string( outStream.str() );
}
Exemplo n.º 4
0
unsigned TimeSigMap::raster(unsigned t, int raster) const
      {
      if (raster == 1)
            return t;
      auto e = upper_bound(t);
      if (e == end()) {
            qDebug("TimeSigMap::raster(%x,)", t);
            return t;
            }
      auto timesig = e->second.timesig();
      return rasterEval(t, raster, e->first, timesig.numerator(),
                        timesig.denominator(), raster / 2);
      }
Exemplo n.º 5
0
int cmp(mpbq const & a, mpq const & b) {
    if (a.is_integer() && b.is_integer()) {
        return -cmp(b, a.m_num);
    } else {
        static thread_local mpz tmp1;
        static thread_local mpz tmp2;
        // tmp1 <- numerator(a)*denominator(b)
        denominator(tmp1, b); tmp1 *= a.m_num;
        // tmp2 <- numerator(b)*denominator(a)
        numerator(tmp2, b); mul2k(tmp2, tmp2, a.m_k);
        return cmp(tmp1, tmp2);
    }
}
Exemplo n.º 6
0
void
mag(void)
{
	save();
	p1 = pop();
	push(p1);
	numerator();
	yymag();
	push(p1);
	denominator();
	yymag();
	divide();
	restore();
}
Exemplo n.º 7
0
double EAPEstimator::estimateSE(Prior prior, size_t question, int answer) {
	const double theta_hat = estimateTheta(prior,question,answer);

	integrableFunction denominator = [&](double theta) {
		return likelihood(theta,question,answer) * prior.prior(theta);
	};

	integrableFunction numerator = [&](double theta) {
		const double theta_difference = theta - theta_hat;
		return theta_difference * theta_difference * denominator(theta);
	};

	return std::pow(integralQuotient(numerator, denominator, questionSet.lowerBound, questionSet.upperBound), 0.5);
}
Exemplo n.º 8
0
void pb_util::normalize(unsigned num_args, rational const* coeffs, rational const& k) {
    m_coeffs.reset();
    bool all_ones = true;
    for (unsigned i = 0; i < num_args && all_ones; ++i) {
        all_ones = denominator(coeffs[i]).is_one();
    }
    if (all_ones) {
        for (unsigned i = 0; i < num_args; ++i) {
            m_coeffs.push_back(coeffs[i]);
        }
        m_k = k;        
    }
    else {
        rational d(1);
        for (unsigned i = 0; i < num_args; ++i) {
            d = lcm(d, denominator(coeffs[i]));
        }
        for (unsigned i = 0; i < num_args; ++i) {
            m_coeffs.push_back(d*coeffs[i]);
        }
        m_k = d*k;
    }
}
Exemplo n.º 9
0
 Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a) {
     Z3_TRY;
     LOG_Z3_get_denominator(c, a);
     RESET_ERROR_CODE();
     rational val;
     ast * _a = to_ast(a);
     if (!is_expr(_a) || !mk_c(c)->autil().is_numeral(to_expr(_a), val)) {
         SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);
         RETURN_Z3(nullptr);
     }
     expr * r = mk_c(c)->autil().mk_numeral(denominator(val), true);
     mk_c(c)->save_ast_trail(r);
     RETURN_Z3(of_expr(r));
     Z3_CATCH_RETURN(nullptr);
 }
Exemplo n.º 10
0
ptr tex::fin_mlist(ptr p)
	{
	ptr	q;

	if (incompleat_noad != null) {
		math_type(denominator(incompleat_noad)) = SUB_MLIST;
		math_link(denominator(incompleat_noad)) = link(head);
		if (p == null) {
			q = incompleat_noad;
		} else {
			q = info(numerator(incompleat_noad));
			if (type(q) != LEFT_NOAD)
				confusion("right");
			math_link(numerator(incompleat_noad)) = link(q);
			link(q) = incompleat_noad;
			link(incompleat_noad) = p;
		}
	} else {
		link(tail) = p;
		q = link(head);
	}
	pop_nest();
	return q;
}
Exemplo n.º 11
0
Foam::tmp<Foam::Field<Foam::scalar>>
Foam::ParticleStressModels::HarrisCrighton::tau
(
    const Field<scalar>& alpha,
    const Field<scalar>& rho,
    const Field<scalar>& uSqr
) const
{
    return
    (
        pSolid_
      * pow(alpha, beta_)
      / denominator(alpha)
    );
}
void RenderMathMLFraction::computePreferredLogicalWidths()
{
    ASSERT(preferredLogicalWidthsDirty());

    m_minPreferredLogicalWidth = 0;
    m_maxPreferredLogicalWidth = 0;

    if (isValid()) {
        LayoutUnit numeratorWidth = numerator().maxPreferredLogicalWidth();
        LayoutUnit denominatorWidth = denominator().maxPreferredLogicalWidth();
        m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = std::max(numeratorWidth, denominatorWidth);
    }

    setPreferredLogicalWidthsDirty(false);
}
Exemplo n.º 13
0
void tex::math_fraction ()
	{
	int	c;
	mcell	garbage;

	c = cur_chr;
	if (incompleat_noad != null) {
		if (c >= DELIMITED_CODE) {
			scan_delimiter((ptr)&garbage, FALSE);
			scan_delimiter((ptr)&garbage, FALSE);
		}
		if (c % DELIMITED_CODE == ABOVE_CODE)
			scan_normal_dimen();
		print_err("Ambiguous; you need another { and }");
		help_fraction();
		error();
	} else {
		incompleat_noad = new_node(FRACTION_NOAD_SIZE);
		type(incompleat_noad) = FRACTION_NOAD;
		subtype(incompleat_noad) = NORMAL;
		math_type(numerator(incompleat_noad)) = SUB_MLIST;
		math_link(numerator(incompleat_noad)) = link(head);
		mzero(denominator(incompleat_noad));
		mzero(left_delimiter(incompleat_noad));
		mzero(right_delimiter(incompleat_noad));
		link(head) = null;
		tail = head;
		if (c >= DELIMITED_CODE) {
			scan_delimiter(left_delimiter(incompleat_noad), FALSE);
			scan_delimiter(right_delimiter(incompleat_noad), FALSE);
		}
		switch (c % DELIMITED_CODE)
		{
		case ABOVE_CODE:
			scan_normal_dimen();
			thickness(incompleat_noad) = cur_val;
			break;

		case OVER_CODE:
			thickness(incompleat_noad) = DEFAULT_CODE;
			break;

		case ATOP_CODE:
			thickness(incompleat_noad) = 0;
			break;
		}
	}
}
Exemplo n.º 14
0
Lisp_Object make_ratio(Lisp_Object p, Lisp_Object q)
/*
 * By the time this is called (p/q) must be in its lowest terms, q>0
 */
{
    Lisp_Object v, nil = C_nil;
    if (q == fixnum_of_int(1)) return p;
    stackcheck2(0, p, q);
    push2(p, q);
    v = getvector(TAG_NUMBERS, TYPE_RATNUM, sizeof(Rational_Number));
    pop2(q, p);
    errexit();
    numerator(v) = p;
    denominator(v) = q;
    return v;
}
Exemplo n.º 15
0
/* Computes a rational given a decimal string. The rational
 * version of <code>xxx.yyy</code> is <code>xxxyyy/(10^3)</code>.
 */
Rational Rational::fromDecimal(const std::string& dec) {
  // Find the decimal point, if there is one
  string::size_type i( dec.find(".") );
  if( i != string::npos ) {
    /* Erase the decimal point, so we have just the numerator. */
    Integer numerator( string(dec).erase(i,1) );

    /* Compute the denominator: 10 raise to the number of decimal places */
    int decPlaces = dec.size() - (i + 1);
    Integer denominator( Integer(10).pow(decPlaces) );

    return Rational( numerator, denominator );
  } else {
    /* No decimal point, assume it's just an integer. */
    return Rational( dec );
  }
}
Exemplo n.º 16
0
 void spacer_matrix::normalize()
 {
     rational den = rational::one();
     for (unsigned i=0; i < m_num_rows; ++i)
     {
         for (unsigned j=0; j < m_num_cols; ++j)
         {
             den = lcm(den, denominator(m_matrix[i][j]));
         }
     }
     for (unsigned i=0; i < m_num_rows; ++i)
     {
         for (unsigned j=0; j < m_num_cols; ++j)
         {
             m_matrix[i][j] = den * m_matrix[i][j];
             SASSERT(m_matrix[i][j].is_int());
         }
     }
 }
Exemplo n.º 17
0
/**
 * Madara function that returns a random fraction between 0 and 1
 **/
madara::knowledge::KnowledgeRecord
  rand_double (madara::knowledge::FunctionArguments & args,
             madara::knowledge::Variables & variables)
{
  // empty arguments list to pass to rand_int (the function above)
  madara::knowledge::FunctionArguments rand_args;

  // the denominator is set to RAND_MAX
  madara::knowledge::KnowledgeRecord::Integer denominator (RAND_MAX);

  // the numerator is set to the results of rand ()
  madara::knowledge::KnowledgeRecord numerator (
    rand_int (rand_args, variables));

  madara::knowledge::KnowledgeRecord result = numerator.to_double () /
    denominator;

  return result;
}
Exemplo n.º 18
0
  double BinnedSharedPeakCount::operator()(const BinnedSpectrum& spec1, const BinnedSpectrum& spec2) const
  {
    if (!spec1.checkCompliance(spec2))
    {
      cout << "incompatible" << endl;
      throw BinnedSpectrumCompareFunctor::IncompatibleBinning(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "");
    }

    // shortcut similarity calculation by comparing PrecursorPeaks (PrecursorPeaks more than delta away from each other are supposed to be from another peptide)
    double pre_mz1 = 0.0;
    if (!spec1.getRawSpectrum().getPrecursors().empty())
    {
      pre_mz1 = spec1.getRawSpectrum().getPrecursors()[0].getMZ();
    }
    double pre_mz2 = 0.0;
    if (!spec2.getRawSpectrum().getPrecursors().empty())
    {
      pre_mz2 = spec2.getRawSpectrum().getPrecursors()[0].getMZ();
    }
    if (fabs(pre_mz1 - pre_mz2) > precursor_mass_tolerance_)
    {
      return 0;
    }

    double score(0), sum(0);
    UInt denominator(max(spec1.getFilledBinNumber(), spec2.getFilledBinNumber())), shared_Bins(min(spec1.getBinNumber(), spec2.getBinNumber()));

    // all bins at equal position that have both intensity > 0 contribute positively to score
    for (Size i = 0; i < shared_Bins; ++i)
    {
      if (spec1.getBins()[i] > 0 && spec2.getBins()[i] > 0)
      {
        sum++;
      }
    }

    // resulting score normalized to interval [0,1]
    score = sum / denominator;

    return score;

  }
TransferFunction::TransferFunction(int x,int y)
{
	mdl=new RectangleView(x,y);

	sNodeType="TransferFunction";
	mosPath="Modelica.Blocks.Continuous.TransferFunction";
	image_index = IM_TRANSFERFUNCTION;

	this->SetInputCount(1);
	this->SetOutputCount(1);
	this->SetInputsName(0, "u");
	this->SetOutputsName(0, "y");

	//参数初始化
	para numerator("b","{1}","","传递函数的分子系数,示例:{1,-5}表示s-5");    //传函的分子系数
	para denominator("a","{1,1}","","传递函数的分母系数");			 //传函的分母系数
	//加入参数列
	para_List.push_back(numerator);
	para_List.push_back(denominator);
}
Exemplo n.º 20
0
bool set(mpbq & a, mpq const & b) {
    if (b.is_integer()) {
        numerator(a.m_num, b);
        a.m_k = 0;
        return true;
    } else {
        static thread_local mpz d;
        denominator(d, b);
        unsigned shift;
        if (d.is_power_of_two(shift)) {
            numerator(a.m_num, b);
            a.m_k = shift;
            lean_assert(a == b);
            return true;
        } else {
            numerator(a.m_num, b);
            a.m_k = d.log2() + 1;
            return false;
        }
    }
}
Exemplo n.º 21
0
 Z3_bool Z3_API Z3_get_numeral_small(Z3_context c, Z3_ast a, int64_t* num, int64_t* den) {
     Z3_TRY;
     // This function invokes Z3_get_numeral_rational, but it is still ok to add LOG command here because it does not return a Z3 object.
     LOG_Z3_get_numeral_small(c, a, num, den);
     RESET_ERROR_CODE();
     CHECK_IS_EXPR(a, Z3_FALSE);
     rational r;
     Z3_bool ok = Z3_get_numeral_rational(c, a, r);
     if (ok == Z3_TRUE) {
         rational n = numerator(r);
         rational d = denominator(r);
         if (n.is_int64() && d.is_int64()) {
             *num = n.get_int64();
             *den = d.get_int64();
             return Z3_TRUE;
         }
         else {
             return Z3_FALSE;
         }
     }
     SET_ERROR_CODE(Z3_INVALID_ARG, nullptr);
     return Z3_FALSE;
     Z3_CATCH_RETURN(Z3_FALSE);
 }
Exemplo n.º 22
0
void
arctan(void)
{
	double d;

	save();

	p1 = pop();

	if (car(p1) == symbol(TAN)) {
		push(cadr(p1));
		restore();
		return;
	}

	if (isdouble(p1)) {
		errno = 0;
		d = atan(p1->u.d);
		if (errno)
			stop("arctan function error");
		push_double(d);
		restore();
		return;
	}

	if (iszero(p1)) {
		push(zero);
		restore();
		return;
	}

	if (isnegative(p1)) {
		push(p1);
		negate();
		arctan();
		negate();
		restore();
		return;
	}

	// arctan(sin(a) / cos(a)) ?

	if (find(p1, symbol(SIN)) && find(p1, symbol(COS))) {
		push(p1);
		numerator();
		p2 = pop();
		push(p1);
		denominator();
		p3 = pop();
		if (car(p2) == symbol(SIN) && car(p3) == symbol(COS) && equal(cadr(p2), cadr(p3))) {
			push(cadr(p2));
			restore();
			return;
		}
	}

	// arctan(1/sqrt(3)) -> pi/6

	if (car(p1) == symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), -1, 2)) {
		push_rational(1, 6);
		push(symbol(PI));
		multiply();
		restore();
		return;
	}

	// arctan(1) -> pi/4

	if (equaln(p1, 1)) {
		push_rational(1, 4);
		push(symbol(PI));
		multiply();
		restore();
		return;
	}

	// arctan(sqrt(3)) -> pi/3

	if (car(p1) == symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), 1, 2)) {
		push_rational(1, 3);
		push(symbol(PI));
		multiply();
		restore();
		return;
	}

	push_symbol(ARCTAN);
	push(p1);
	list(2);

	restore();
}
Exemplo n.º 23
0
float cost_evaluator::eval(expr * f) const {
#define E(IDX) eval(to_app(f)->get_arg(IDX))
    if (is_app(f)) {
        unsigned num_args;
        family_id fid = to_app(f)->get_family_id();
        if (fid == m_manager.get_basic_family_id()) {
            switch (to_app(f)->get_decl_kind()) {
            case OP_TRUE:     return 1.0f;
            case OP_FALSE:    return 0.0f;
            case OP_NOT:      return E(0) == 0.0f ? 1.0f : 0.0f;
            case OP_AND:      
                num_args = to_app(f)->get_num_args();
                for (unsigned i = 0; i < num_args; i++) 
                    if (E(i) == 0.0f)
                        return 0.0f;
                return 1.0f;
            case OP_OR:
                num_args = to_app(f)->get_num_args();
                for (unsigned i = 0; i < num_args; i++) 
                    if (E(i) != 0.0f)
                        return 1.0f;
                return 0.0f;
            case OP_ITE:      return E(0) != 0.0f ? E(1) : E(2);
            case OP_EQ:
            case OP_IFF:      return E(0) == E(1) ? 1.0f : 0.0f;
            case OP_XOR:      return E(0) != E(1) ? 1.0f : 0.0f;
            case OP_IMPLIES:  
                if (E(0) == 0.0f)
                    return 1.0f;
                return E(1) != 0.0f ? 1.0f : 0.0f;
            default:
                ;
            }
        }
        else if (fid == m_util.get_family_id()) {
            switch (to_app(f)->get_decl_kind()) {
            case OP_NUM: {
                rational r = to_app(f)->get_decl()->get_parameter(0).get_rational();
                return static_cast<float>(numerator(r).get_int64())/static_cast<float>(denominator(r).get_int64());
            } 
            case OP_LE:       return E(0) <= E(1) ? 1.0f : 0.0f;
            case OP_GE:       return E(0) >= E(1) ? 1.0f : 0.0f;
            case OP_LT:       return E(0) <  E(1) ? 1.0f : 0.0f;
            case OP_GT:       return E(0) >  E(1) ? 1.0f : 0.0f;
            case OP_ADD:      return E(0) + E(1);
            case OP_SUB:      return E(0) - E(1);
            case OP_UMINUS:   return - E(0);
            case OP_MUL:      return E(0) * E(1);
            case OP_DIV: {     
                float q = E(1);
                if (q == 0.0f) {
                    warning_msg("cost function division by zero");
                    return 1.0f;
                }
                return E(0) / q;
            }
            default:
                ;
            }
        }
    }
    else if (is_var(f)) {
        unsigned idx = to_var(f)->get_idx();
        if (idx < m_num_args)
            return m_args[m_num_args - idx - 1];
    }
    warning_msg("cost function evaluation error");
    return 1.0f;
}
Exemplo n.º 24
0
void TimeDialog::nChanged(int /*val*/)
      {
      nText->setText(QString("%1").arg(denominator()));
      Fraction sig(zNominal->value(), denominator());
      groups->setSig(sig, Groups::endings(sig));
      }
Exemplo n.º 25
0
static CSLbool numeqsr(Lisp_Object a, Lisp_Object b)
/*
 * Here I will rely somewhat on the use of IEEE floating point values
 * (an in particular the weaker supposition that I have floating point
 * with a binary radix).  Then for equality the denominator of b must
 * be a power of 2, which I can test for and then account for.
 */
{
    Lisp_Object nb = numerator(b), db = denominator(b);
    double d = float_of_number(a), d1;
    int x;
    int32_t dx, w, len;
    uint32_t u, bit;
    /*
     * first I will check that db (which will be positive) is a power of 2,
     * and set dx to indicate what power of two it is.
     * Note that db != 0 and that one of the top two words of a bignum
     * must be nonzero (for normalisation) so I end up with a nonzero
     * value in the variable 'bit'
     */
    if (is_fixnum(db))
    {   bit = int_of_fixnum(db);
        w = bit;
        if (w != (w & (-w))) return NO;   /* not a power of 2 */
        dx = 0;
    }
    else if (is_numbers(db) && is_bignum(db))
    {   int32_t lenb = (bignum_length(db)-CELL-4)/4;
        bit = bignum_digits(db)[lenb];
        /*
         * I need to cope with bignums where the leading digits is zero because
         * the 0x80000000 bit of the next word down is 1.  To do this I treat
         * the number as having one fewer digits.
         */
        if (bit == 0) bit = bignum_digits(db)[--lenb];
        w = bit;
        if (w != (w & (-w))) return NO;   /* not a power of 2 */
        dx = 31*lenb;
        while (--lenb >= 0)     /* check that the rest of db is zero */
            if (bignum_digits(db)[lenb] != 0) return NO;
    }
    else return NO; /* Odd - what type IS db here?  Maybe error. */
    if ((bit & 0xffffU) == 0) dx += 16, bit = bit >> 16;
    if ((bit & 0xff) == 0) dx += 8, bit = bit >> 8;
    if ((bit & 0xf) == 0) dx += 4, bit = bit >> 4;
    if ((bit & 0x3) == 0) dx += 2, bit = bit >> 2;
    if ((bit & 0x1) == 0) dx += 1;
    if (is_fixnum(nb))
    {   double d1 = (double)int_of_fixnum(nb);
        /*
         * The ldexp on the next line could potentially underflow.  In that case C
         * defines that the result 0.0 be returned.  To avoid trouble I put in a
         * special test the relies on that fact that a value represented as a rational
         * would not have been zero.
         */
        if (dx > 10000) return NO;  /* Avoid gross underflow */
        d1 = ldexp(d1, (int)-dx);
        return (d == d1 && d != 0.0);
    }
    len = (bignum_length(nb)-CELL-4)/4;
    if (len == 0)   /* One word bignums can be treated specially */
    {   int32_t v = bignum_digits(nb)[0];
        double d1;
        if (dx > 10000) return NO;  /* Avoid gross underflow */
        d1 = ldexp((double)v, (int)-dx);
        return (d == d1 && d != 0.0);
    }
    d1 = frexp(d, &x);    /* separate exponent from mantissa */
    if (d1 == 1.0) d1 = 0.5, x++; /* For Zortech */
    dx += x;              /* adjust to allow for the denominator */
    d1 = ldexp(d1, (int)(dx % 31));
    /* can neither underflow nor overflow here */
    /*
     * At most 3 words in the bignum may contain nonzero data - I subtract
     * the (double) value of those bits off and check that (a) the floating
     * result left is zero and (b) there are no more bits left.
     */
    dx = dx / 31;
    if (dx != len) return NO;
    w = bignum_digits(nb)[len];
    d1 = (d1 - (double)w) * TWO_31;
    u = bignum_digits(nb)[--len];
    d1 = (d1 - (double)u) * TWO_31;
    if (len > 0)
    {   u = bignum_digits(nb)[--len];
        d1 = d1 - (double)u;
    }
    if (d1 != 0.0) return NO;
    while (--len >= 0)
        if (bignum_digits(nb)[len] != 0) return NO;
    return YES;
}
Exemplo n.º 26
0
static CSLbool numeqrr(Lisp_Object a, Lisp_Object b)
{
    return numeq2(numerator(a), numerator(b)) &&
           numeq2(denominator(a), denominator(b));
}
Exemplo n.º 27
0
std::shared_ptr<AVFrame> make_av_video_frame(const core::const_frame& frame, const core::video_format_desc& format_desc)
{
    auto av_frame = alloc_frame();

    auto pix_desc = frame.pixel_format_desc();

    auto planes = pix_desc.planes;
    auto format = pix_desc.format;

    const auto sar = boost::rational<int>(format_desc.square_width, format_desc.square_height) /
                     boost::rational<int>(format_desc.width, format_desc.height);

    av_frame->sample_aspect_ratio = {sar.numerator(), sar.denominator()};
    av_frame->width               = format_desc.width;
    av_frame->height              = format_desc.height;

    switch (format) {
        case core::pixel_format::rgb:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_RGB24;
            break;
        case core::pixel_format::bgr:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_BGR24;
            break;
        case core::pixel_format::rgba:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_RGBA;
            break;
        case core::pixel_format::argb:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_ARGB;
            break;
        case core::pixel_format::bgra:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_BGRA;
            break;
        case core::pixel_format::abgr:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_ABGR;
            break;
        case core::pixel_format::gray:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_GRAY8;
            break;
        case core::pixel_format::ycbcr: {
            int y_w = planes[0].width;
            int y_h = planes[0].height;
            int c_w = planes[1].width;
            int c_h = planes[1].height;

            if (c_h == y_h && c_w == y_w)
                av_frame->format = AVPixelFormat::AV_PIX_FMT_YUV444P;
            else if (c_h == y_h && c_w * 2 == y_w)
                av_frame->format = AVPixelFormat::AV_PIX_FMT_YUV422P;
            else if (c_h == y_h && c_w * 4 == y_w)
                av_frame->format = AVPixelFormat::AV_PIX_FMT_YUV411P;
            else if (c_h * 2 == y_h && c_w * 2 == y_w)
                av_frame->format = AVPixelFormat::AV_PIX_FMT_YUV420P;
            else if (c_h * 2 == y_h && c_w * 4 == y_w)
                av_frame->format = AVPixelFormat::AV_PIX_FMT_YUV410P;

            break;
        }
        case core::pixel_format::ycbcra:
            av_frame->format = AVPixelFormat::AV_PIX_FMT_YUVA420P;
            break;
    }

    FF(av_frame_get_buffer(av_frame.get(), 32));

    // TODO (perf) Avoid extra memcpy.
    for (int n = 0; n < planes.size(); ++n) {
        for (int y = 0; y < av_frame->height; ++y) {
            std::memcpy(av_frame->data[n] + y * av_frame->linesize[n],
                        frame.image_data(n).data() + y * planes[n].linesize,
                        planes[n].linesize);
        }
    }

    return av_frame;
}
Exemplo n.º 28
0
Polynom::Polynom(const string str)
{
   int tmp, tmp1, tmp2;

   coefficients.clear();
   if (str.length() < 8)
	   throw(invalid_argument("incorrect number input. You can try help\n"));

   for (auto i = 0; i < str.length(); i++)
	  if (!isdigit(str[i]) && str[i] != 'x' && str[i] != '^' && str[i] != '+' && str[i] != '-' && str[i] != '/' && str[i] != '(' && str[i] != ')')
		  throw(invalid_argument("incorrect number input. You can try help\n"));
	 
   tmp = 0;
   if (str[0] == '-' || str[0] == '+')
	  tmp++;

   do
   {
	  tmp1 = str.find("(", tmp);
	  if (tmp1 != tmp)
		  throw(invalid_argument("incorrect number input. You can try help\n"));

	  tmp = ++tmp1;
	  while (tmp < str.size() && isdigit(str[tmp]))
		 tmp++;
	  if (tmp == tmp1)
		  throw(invalid_argument("incorrect number input. You can try help\n"));

	  if (tmp != -1)
	  {
		 tmp1 = str.find("/", tmp);
		 if (tmp1 == -1 || (tmp1 - tmp) != 0)
			 throw(invalid_argument("incorrect number input. You can try help\n"));

		 tmp = ++tmp1;
		 while (tmp < str.size() && isdigit(str[tmp]))
			tmp++;
		 if (tmp == tmp1)
			 throw(invalid_argument("incorrect number input. You can try help\n"));

		 tmp1 = str.find(")", tmp);
		 if (tmp1 == -1 || (tmp1 - tmp) != 0)
			 throw(invalid_argument("incorrect number input. You can try help\n"));

		 tmp = ++tmp1;
		 tmp1 = str.find("x^", tmp);
		 if (tmp1 == -1 || (tmp1 - tmp) != 0)
			 throw(invalid_argument("incorrect number input. You can try help\n"));

		 tmp1 += 2;
		 while (tmp1 < str.size() && isdigit(str[tmp1]))
			tmp1++;

		 if (tmp == tmp1)
			 throw(invalid_argument("incorrect number input. You can try help\n"));

		 if (tmp1 == str.size())
			break;

		 tmp2 = tmp = tmp1;
		 tmp = str.find("+", tmp);
		 tmp1 = str.find("-", tmp1);
		 if (tmp == -1 && tmp1 == -1)
			 throw(invalid_argument("incorrect number input. You can try help\n"));
		 
		 if (tmp == -1)
			tmp = tmp1;

		 if (tmp1 < tmp)
			tmp = tmp1;

		 if ((tmp - tmp2) != 0)
			 throw(invalid_argument("incorrect number input. You can try help\n"));
		 tmp++;
	  }
	  else
		  throw(invalid_argument("incorrect number input. You can try help\n"));
   }
   while (true);

   MegaNatural lastCoef,b_lastCoef;
   int sign;
   MegaRational coef();
   bool first = true;
   int pos = 0;
   
   do
   {
	  if (first)
	  {
		 first = false;
		 if (str[0] == '-')
			sign = -1;
		 else
			sign = 1;

		 MegaInteger numerator(getNextNum(str, pos));
		 numerator = numerator*(MegaInteger)(-1);
		 MegaNatural denominator(getNextNum(str, pos));
		 coefficients.push_front(MegaRational(numerator, denominator));
		 lastCoef = getNextNum(str, pos);
		 continue;
	  }
	  tmp = str.find("+", pos);
	  tmp1 = str.find("-", pos);
	  if (tmp == -1 && tmp1 == -1)
		 break;

	  if (tmp != -1 && tmp1 != -1)
		 if (tmp < tmp1)
			sign = 1;
		 else
			sign = -1;

	  if (tmp == -1)
		 sign = -1;

	  if (tmp1 == -1)
		 sign = 1;

	  MegaInteger numerator(getNextNum(str, pos));
	  numerator = numerator*(MegaInteger) (-1);
	  MegaNatural denominator(getNextNum(str, pos));
	  coefficients.push_front(MegaRational(numerator, denominator));

	  b_lastCoef = lastCoef;
	  lastCoef = getNextNum(str, pos);
	  if (lastCoef >= b_lastCoef)
	  {
		 coefficients.clear();
		 coefficients.resize(0);
		 throw(invalid_argument("incorrect number input. You can try help\n"));
	  } 
	  else
	  {
		 while ((b_lastCoef - (MegaNatural) 1) > lastCoef)
		 {
			b_lastCoef = b_lastCoef - (MegaNatural) 1;
			coefficients.push_front(MegaRational());
		 }
	  }
   }
   while (pos < str.size());
   while (lastCoef>(MegaNatural)0)
   {
	   lastCoef = lastCoef - (MegaNatural)1;
	   coefficients.push_front(MegaRational());

   }
}
Exemplo n.º 29
0
sample_rate
sample_rate::common( const sample_rate &o ) const
{
	auto x = _ratio.common( o._ratio );
	return sample_rate( x.numerator(), x.denominator() );
}
Exemplo n.º 30
0
void manualFRTest()
{

  TFile* f = TFile::Open("/eos/user/v/vischia/www/taufakes_new/plotter_wjet.root", "READ");
  
  TString
    data("data (single mu)"),
    ttbar("TTbar"),
    wjets("W#rightarrow l#nu inclusive"),
    qcd("QCD_EMEnr_Incl");
  
  
  TString
    numerator("/wjet_step5byLooseCombinedIsolationDeltaBetaCorr3Hitseta_numerator"),
    denominator("/wjet_step5eta_denominator");

  

  TH1F* data_num = (TH1F*) f->Get(data+numerator);
  TH1F* data_den = (TH1F*) f->Get(data+denominator);

  TH1F* ttbar_num = (TH1F*) f->Get(ttbar+numerator);
  TH1F* ttbar_den = (TH1F*) f->Get(ttbar+denominator);

  TH1F* wjets_num = (TH1F*) f->Get(wjets+numerator);
  TH1F* wjets_den = (TH1F*) f->Get(wjets+denominator);

  TH1F* qcd_num = (TH1F*) f->Get(qcd+numerator);
  TH1F* qcd_den = (TH1F*) f->Get(qcd+denominator);
  

  TH1F* mc_num = (TH1F*) ttbar_num->Clone("mc_num");
  mc_num->Add(wjets_num);
  //mc_num->Add(qcd_num);

  TH1F* mc_den = (TH1F*) ttbar_den->Clone("mc_den");
  mc_den->Add(wjets_den);
  //mc_den->Add(qcd_den);

  data_num->SetMarkerColor(kBlack);
  mc_num->SetMarkerColor(kRed);

  data_den->SetMarkerColor(kBlack);
  mc_den->SetMarkerColor(kRed);

  TCanvas* d = new TCanvas("d", "d", 600, 1200);
  d->Divide(1,2);
  d->cd(1);
  gPad->SetTitle("numerator");
  data_num->DrawCopy("pe");
  mc_num->DrawCopy("pesame");
  d->cd(2);
  gPad->SetTitle("denominator");
  data_den->DrawCopy("pe");
  mc_den->DrawCopy("pesame");
  


  TH1F* data_fr = (TH1F*) data_num->Clone("data_fr");
  data_fr->Divide(data_den);
  
  TH1F* mc_fr = (TH1F*) mc_num->Clone("mc_fr");
  mc_fr->Divide(mc_den);
  
  data_fr->SetMarkerColor(kBlack);
  mc_fr->SetMarkerColor(kRed);
  
  data_fr->SetMarkerSize(2);
  mc_fr->SetMarkerSize(2);

  TCanvas* c = new TCanvas("c", "c", 600, 600);
  c->cd();

  data_fr->Draw("pe");
  mc_fr->Draw("pesame");
  
  

              


}