python类ROUND_HALF_UP的实例源码

st_scheme_template.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def fmt_float(f, p=0):
    """Set float precision and trim precision zeros."""

    string = str(
        decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP)
    )

    m = re_float_trim.match(string)
    if m:
        string = m.group('keep')
        if m.group('keep2'):
            string += m.group('keep2')
    return string
mathutils.py 文件源码 项目:aio 作者: pavhofman 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def roundToInt(timePos: float) -> int:
    return int(decimal.Decimal(timePos).quantize(decimal.Decimal(1),
                                                 rounding=decimal.ROUND_HALF_UP))
abcbase.py 文件源码 项目:zStock 作者: superxhy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def CCI_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
        #sma target round2
        precision = 14
        high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
        if np.isnan(close[-1]):
            return np.array([np.nan])
        CCI = self.CCI_CN(high, low, close)
        if len(CCI) > precision:
            CCI = CCI[-dataCount:]
        else:
            #print "security:%s no len data precison %s" %(str(security), len(CCI))
            pass
        decimal.getcontext().rounding=decimal.ROUND_HALF_UP
        CCI = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in CCI])
        return CCI
money.py 文件源码 项目:py-money 作者: vimeo 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _round(amount: Decimal, currency: Currency) -> Decimal:
        sub_units = CurrencyHelper.sub_unit_for_currency(currency)
        # rstrip is necessary because quantize treats 1. differently from 1.0
        rounded_to_subunits = amount.quantize(Decimal(str(1 / sub_units).rstrip('0')),\
                                              rounding=ROUND_HALF_UP)
        decimal_precision = CurrencyHelper.decimal_precision_for_currency(currency)
        return rounded_to_subunits.quantize(\
                   Decimal(str(1 / (10 ** decimal_precision)).rstrip('0')),\
                   rounding=ROUND_HALF_UP)
_compat.py 文件源码 项目:minihydra 作者: VillanCh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def round_py2_compat(what):
    """
    Python 2 and Python 3 use different rounding strategies in round(). This
    function ensures that results are python2/3 compatible and backward
    compatible with previous py2 releases
    :param what: float
    :return: rounded long
    """
    d = Context(
        prec=len(str(long(what))),  # round to integer with max precision
        rounding=decimal.ROUND_HALF_UP
    ).create_decimal(str(what))  # str(): python 2.6 compat
    return long(d)
money.py 文件源码 项目:dj-txmoney 作者: txerpa 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def amount_rounded(self):
        """
        Amount in decimal currency precision
        :return:
        """
        decimals = Decimal(10) ** -self._currency.decimals
        return self._amount.quantize(decimals, rounding=ROUND_HALF_UP)
money.py 文件源码 项目:dj-txmoney 作者: txerpa 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def round(self, n=None):
        n = n or self._currency.decimals
        decimals = Decimal(10) ** -n
        return self.__class__(self._amount.quantize(decimals, rounding=ROUND_HALF_UP), self._currency)
projection.py 文件源码 项目:wrf-python 作者: NCAR 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __eq__(self, other):
        """Return True if this projection object is the same as *other*.

        Note:  WRF can use either floats or doubles, so only going to 
        guarantee floating point precision equivalence, in case the different 
        types are ever compared (or a projection is hand constructed). For WRF
        domains, 7-digit equivalence should be good enough.

        """

        if self.map_proj is not None:
            if self.map_proj != other.map_proj:
                return False
        else:
            if other.map_proj is not None:
                return False

        # Only checking for floating point equal.
        ctx = Context(prec=7, rounding=ROUND_HALF_UP)

        return (WrfProj._context_equal(self.truelat1, other.truelat1, ctx) and
                WrfProj._context_equal(self.truelat2, other.truelat2, ctx) and
                WrfProj._context_equal(self.moad_cen_lat, other.moad_cen_lat, 
                                      ctx) and
                WrfProj._context_equal(self.stand_lon, other.stand_lon, 
                                       ctx) and
                WrfProj._context_equal(self.pole_lat, other.pole_lat, ctx) and
                WrfProj._context_equal(self.pole_lon, other.pole_lon, ctx) and
                WrfProj._context_equal(self.dx, other.dx, ctx) and
                WrfProj._context_equal(self.dy, other.dy, ctx))
_compat.py 文件源码 项目:deb-python-eventlet 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def round_py2_compat(what):
    """
    Python 2 and Python 3 use different rounding strategies in round(). This
    function ensures that results are python2/3 compatible and backward
    compatible with previous py2 releases
    :param what: float
    :return: rounded long
    """
    d = Context(
        prec=len(str(long(what))),  # round to integer with max precision
        rounding=decimal.ROUND_HALF_UP
    ).create_decimal(str(what))  # str(): python 2.6 compat
    return long(d)
_compat.py 文件源码 项目:inwx-zonefile-sync 作者: lukas2511 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def round_py2_compat(what):
    """
    Python 2 and Python 3 use different rounding strategies in round(). This
    function ensures that results are python2/3 compatible and backward
    compatible with previous py2 releases
    :param what: float
    :return: rounded long
    """
    d = Context(
        prec=len(str(long(what))),  # round to integer with max precision
        rounding=decimal.ROUND_HALF_UP
    ).create_decimal(str(what))  # str(): python 2.6 compat
    return long(d)
xpathast.py 文件源码 项目:yangson 作者: CZ-NIC 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _eval(self, xctx: XPathContext) -> float:
        dec = decimal.Decimal(self.expr._eval_float(xctx))
        try:
            return float(dec.to_integral_value(
                decimal.ROUND_HALF_UP if dec > 0 else decimal.ROUND_HALF_DOWN))
        except decimal.InvalidOperation:
            return float('nan')
rounding.py 文件源码 项目:cohorts 作者: hammerlab 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def round_float(f, digits, rounding=ROUND_HALF_UP):
    """
    Accurate float rounding from http://stackoverflow.com/a/15398691.
    """
    return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits),
                                    rounding=rounding)
operators.py 文件源码 项目:Meiji 作者: GiovanniBalestrieri 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def Builtin_ROUND(expr, ctx):
    """
    http://www.w3.org/TR/sparql11-query/#func-round
    """

    # This used to be just math.bound
    # but in py3k bound was changed to
    # "round-to-even" behaviour
    # this is an ugly work-around
    l = expr.arg
    v = numeric(l)
    v = int(Decimal(v).quantize(1, ROUND_HALF_UP))
    return Literal(v, datatype=l.datatype)
operators.py 文件源码 项目:prophet 作者: MKLab-ITI 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def Builtin_ROUND(expr, ctx):
    """
    http://www.w3.org/TR/sparql11-query/#func-round
    """

    # This used to be just math.bound
    # but in py3k bound was changed to
    # "round-to-even" behaviour
    # this is an ugly work-around
    l = expr.arg
    v = numeric(l)
    v = int(Decimal(v).quantize(1, ROUND_HALF_UP))
    return Literal(v, datatype=l.datatype)
cvss2.py 文件源码 项目:cvss 作者: skontar 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def round_to_1_decimal(value):
    """
    Round to one decimal.
    """
    return value.quantize(D('0.1'), rounding=ROUND_HALF_UP)
qrlnode.py 文件源码 项目:QRL 作者: theQRL 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_dec_amount(str_amount_arg: str) -> Decimal:
        # FIXME: Concentrating logic into a single point. Fix this, make type safe to avoid confusion. Quantity formats should be always clear
        # FIXME: Review. This is just relocated code. It looks odd
        # FIXME: Antipattern. Magic number.
        # FIXME: Validate string, etc.
        return decimal.Decimal(decimal.Decimal(str_amount_arg) * 100000000).quantize(decimal.Decimal('1'),
                                                                                     rounding=decimal.ROUND_HALF_UP)
stages.py 文件源码 项目:aws-greengrass-mini-fulfillment 作者: awslabs 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def polar_goals(x, y):
    """
    Use a polar coordinate system to calculate goals from given X and Y
    values.

    :param x: x cartesian coordinate
    :param y: y cartesian coordinate
    :return: polar coordinate derived base, fibia, and tibia servo goal values
    """
    if y < 0:
        raise ValueError("Cannot accept negative Y values.")

    # base servo value which represents 0 degrees. Strongly dependent upon
    # physical construction, servo installation and location of arm
    polar_axis = 210
    polar_180_deg = 810  # base servo value which represents 180 degrees
    polar_diff = polar_180_deg - polar_axis

    x_shift = Decimal(MAX_IMAGE_WIDTH / 2).quantize(
        exp=Decimal('1.0'), rounding=ROUND_HALF_UP)
    log.info("[polar_goals] x_shift:{0}".format(x_shift))
    # shift origin of x, y to center of base
    shifted_x = x - x_shift
    log.info("[polar_goals] new_x:{0} new_y:{1}".format(shifted_x, y))

    # horizontal kicker to overcome what we think is image parallax
    if 40 < abs(shifted_x) < 10:
        shifted_x *= 1.25
    elif 90 < abs(shifted_x) < 40:
        shifted_x *= 1.40

    # convert shifted x and y to rho and theta
    rho, theta = cart2polar(int(shifted_x), int(y))
    log.info("[polar_goals] r:{0} theta:{1}".format(rho, theta))

    # convert theta into base rotation goal
    bg = int((polar_diff / 180) * theta + polar_axis)
    # ensure base goal does not go beyond the 180 or 0 servo rotation boundaries
    if bg > polar_180_deg:
        bg = polar_180_deg
    if bg < polar_axis:
        bg = polar_axis

    bg_cart, fg, tg = cartesian_goals(x, y)
    # Return polar coordinates for base and cartesian for arm goals. We found
    # this combination to work best through experimentation over hours of
    # operation.
    return bg + 20, fg, tg
sim_utils.py 文件源码 项目:pyxem 作者: pyxem 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def equispaced_s2_grid(theta_range, phi_range, resolution=2.5, no_center=False):
    """Creates rotations approximately equispaced on a sphere.

    Parameters
    ----------
    theta_range : tuple of float
        (theta_min, theta_max)
        The range of allowable polar angles, in degrees.
    phi_range : tuple of float
        (phi_min, phi_max)
        The range of allowable azimuthal angles, in degrees.
    resolution : float
        The angular resolution of the grid in degrees.
    no_center : bool
        If true, `theta` values will not start at zero.

    Returns
    -------
    s2_grid : array-like
        Each row contains `(theta, phi)`, the azimthal and polar angle
        respectively.

    """
    theta_min, theta_max = [radians(t) for t in theta_range]
    phi_min, phi_max = [radians(r) for r in phi_range]
    resolution = radians(resolution)
    resolution = 2 * theta_max / int(Decimal(2 * theta_max / resolution).quantize(0, ROUND_HALF_UP))
    n_theta = int(Decimal((2 * theta_max / resolution + no_center)).quantize(0, ROUND_HALF_UP) / 2)

    if no_center:
        theta_grid = np.arange(0.5, n_theta + 0.5) * resolution
    else:
        theta_grid = np.arange(n_theta + 1) * resolution

    phi_grid = []
    for j, theta in enumerate(theta_grid):
        steps = max(round(sin(theta) * phi_max / theta_max * n_theta), 1)
        phi = phi_min\
            + np.arange(steps) * (phi_max - phi_min) / steps \
            + ((j+1) % 2) * (phi_max - phi_min) / steps / 2
        phi_grid.append(phi)
    s2_grid = np.array(
        [(theta, phi) for phis, theta in zip(phi_grid, theta_grid) for phi in
         phis])
    return s2_grid
make_screenshots.py 文件源码 项目:biweeklybudget 作者: jantman 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _payperiods_preshot(self):
        logger.info('payperiods preshot')
        # BEGIN DB update
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        pp = BiweeklyPayPeriod.period_for_date(dtnow(), data_sess).previous
        data_sess.add(Budget(
            name='Budget3', is_periodic=True, starting_balance=0
        ))
        data_sess.add(Budget(
            name='Budget4', is_periodic=True, starting_balance=0
        ))
        data_sess.flush()
        data_sess.commit()
        budgets = list(data_sess.query(Budget).filter(
            Budget.is_active.__eq__(True),
            Budget.is_income.__eq__(False),
            Budget.is_periodic.__eq__(True)
        ).all())
        for i in range(0, 12):  # payperiods
            mult = choice([-1, 1])
            target = 2011.67 + (mult * uniform(0, 500))
            total = 0
            count = 0
            while total < target:
                count += 1
                amt = uniform(0, target * 0.2)
                if total + amt > target:
                    amt = target - total
                total += amt
                amt = Decimal(Decimal(amt).quantize(
                    Decimal('.001'), rounding=ROUND_HALF_UP
                ))
                data_sess.add(Transaction(
                    account_id=1,
                    budgeted_amount=amt,
                    actual_amount=amt,
                    budget=choice(budgets),
                    date=pp.start_date + timedelta(days=1),
                    description='Transaction %d.%d' % (i, count)
                ))
                data_sess.flush()
                data_sess.commit()
            pp = pp.next
        data_sess.close()
        conn.close()
        # END DB update
        self.get('/payperiods')
        sleep(1)


问题


面经


文章

微信
公众号

扫码关注公众号