python类ROUND_HALF_UP的实例源码

make_screenshots.py 文件源码 项目:biweeklybudget 作者: jantman 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _index_preshot(self):
        logger.info('Index preshot')
        # BEGIN DB update
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        for acct in data_sess.query(Account).all():
            end_bal = acct.balance.ledger
            pctrange = float(end_bal) * 0.1
            for i in range(1, 30):
                dt = dtnow() - timedelta(days=i)
                b = end_bal + Decimal(uniform(-1 * pctrange, pctrange))
                b = Decimal(b.quantize(Decimal('.001'), rounding=ROUND_HALF_UP))
                acct.set_balance(ledger=b, ledger_date=dt, overall_date=dt)
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        # END DB update
        self.get('/')
        sleep(1)
abcbase.py 文件源码 项目:zStock 作者: superxhy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def KDJ_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
        #sma target round2
        precision = 40
        high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
        if np.isnan(close[-1]):
            return np.array([np.nan]),np.array([np.nan]),np.array([np.nan])
        #K_V, D_V, J_V = self.KDJ_CN(high, low, close)
        K_V, D_V, J_V = self.KDJ_COM(high, low, close)
        if len(K_V) > precision:
            K_V = K_V[precision:]
            D_V = D_V[precision:]
            J_V = J_V[precision:]
        else:
            #print "security:%s no len data precison %s" %(str(security), len(K_V))
            pass
        decimal.getcontext().rounding=decimal.ROUND_HALF_UP
        K_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in K_V])
        D_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in D_V])
        J_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in J_V])
        return K_V, D_V, J_V
fields.py 文件源码 项目:flask-zhenai-mongo-echarts 作者: Fretice 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, min_value=None, max_value=None, force_string=False,
                 precision=2, rounding=decimal.ROUND_HALF_UP, **kwargs):
        """
        :param min_value: Validation rule for the minimum acceptable value.
        :param max_value: Validation rule for the maximum acceptable value.
        :param force_string: Store as a string.
        :param precision: Number of decimal places to store.
        :param rounding: The rounding rule from the python decimal library:

            - decimal.ROUND_CEILING (towards Infinity)
            - decimal.ROUND_DOWN (towards zero)
            - decimal.ROUND_FLOOR (towards -Infinity)
            - decimal.ROUND_HALF_DOWN (to nearest with ties going towards zero)
            - decimal.ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)
            - decimal.ROUND_HALF_UP (to nearest with ties going away from zero)
            - decimal.ROUND_UP (away from zero)
            - decimal.ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)

            Defaults to: ``decimal.ROUND_HALF_UP``

        """
        self.min_value = min_value
        self.max_value = max_value
        self.force_string = force_string
        self.precision = precision
        self.rounding = rounding

        super(DecimalField, self).__init__(**kwargs)
progressbar.py 文件源码 项目:python-glareclient 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _display_progress_bar(self, size_read):
        self._totalread += size_read
        if self._show_progress:
            if self._totalsize:
                percent = float(self._totalread) / float(self._totalsize)
                # Output something like this: [==========>             ] 49%
                sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
                    '=' * int(decimal.Decimal(percent * 29).quantize(
                        decimal.Decimal('1'),
                        rounding=decimal.ROUND_HALF_UP)) + '>', percent
                ))
            else:
                sys.stdout.write(
                    '\r[%s] %d bytes' % (SPIN_CHARS[self._spin_index],
                                         self._totalread))
                self._spin_index += 1
                if self._spin_index == len(SPIN_CHARS):
                    self._spin_index = 0
            sys.stdout.flush()
formulas.py 文件源码 项目:QRL 作者: theQRL 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def remaining_emission(N_tot, block_n):
    # TODO: This is more related to the way QRL works.. Move to another place
    """
    calculate remaining emission at block_n: N=total initial coin supply, coeff = decay constant
    need to use decimal as floating point not precise enough on different platforms..
    :param N_tot:
    :param block_n:
    :return:

    >>> remaining_emission(1, 1)
    Decimal('0.99999996')
    """
    # TODO: Verify these values and formula
    coeff = calc_coeff(config.dev.max_coin_supply, 420480000)

    # FIXME: Magic number? Unify
    return decimal.Decimal(N_tot * decimal.Decimal(-coeff * block_n).exp()) \
        .quantize(decimal.Decimal('1.00000000'), rounding=decimal.ROUND_HALF_UP)
py23.py 文件源码 项目:otRebuilder 作者: Pal3love 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def round2(number, ndigits=None):
        """
        Implementation of Python 2 built-in round() function.

        Rounds a number to a given precision in decimal digits (default
        0 digits). The result is a floating point number. Values are rounded
        to the closest multiple of 10 to the power minus ndigits; if two
        multiples are equally close, rounding is done away from 0.

        ndigits may be negative.

        See Python 2 documentation:
        https://docs.python.org/2/library/functions.html?highlight=round#round
        """
        if ndigits is None:
            ndigits = 0

        if ndigits < 0:
            exponent = 10 ** (-ndigits)
            quotient, remainder = divmod(number, exponent)
            if remainder >= exponent//2 and number >= 0:
                quotient += 1
            return float(quotient * exponent)
        else:
            exponent = _decimal.Decimal('10') ** (-ndigits)

            d = _decimal.Decimal.from_float(number).quantize(
                exponent, rounding=_decimal.ROUND_HALF_UP)

            return float(d)
decimal_field.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, min_value=None, max_value=None, precision=2, rounding=decimal.ROUND_HALF_UP, *args, **kw):
        super(DecimalField, self).__init__(*args, **kw)
        self.min_value = min_value
        if self.min_value is not None:
            self.min_value = decimal.Decimal(min_value)

        self.max_value = max_value
        if self.max_value is not None:
            self.max_value = decimal.Decimal(max_value)

        self.precision = decimal.Decimal(".%s" % ("0" * precision))
        self.rounding = rounding
rgba.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def round_int(dec):
    """Round float to nearest int using expected rounding."""

    return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))
st_scheme_template.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 18 收藏 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
__init__.py 文件源码 项目:postix 作者: c3cashdesk 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def round_decimal(d: decimal.Decimal) -> decimal.Decimal:
    return decimal.Decimal(d).quantize(DECIMAL_QUANTIZE, decimal.ROUND_HALF_UP)
tag.py 文件源码 项目:eyeD3 作者: nicfit 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _getBpm(self):
        from decimal import Decimal, ROUND_HALF_UP, InvalidOperation

        bpm = None
        if frames.BPM_FID in self.frame_set:
            bpm_str = self.frame_set[frames.BPM_FID][0].text or u"0"
            try:
                # Round floats since the spec says this is an integer. Python3
                # changed how 'round' works, hence the using of decimal
                bpm = int(Decimal(bpm_str).quantize(1, ROUND_HALF_UP))
            except (InvalidOperation, ValueError) as ex:
                log.warning(ex)
        return bpm
number.py 文件源码 项目:filters 作者: eflglobal 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def __init__(self,
            to_nearest  = 1,
            rounding    = ROUND_HALF_UP,
            result_type = DecimalType,
    ):
        # type: (Union[int, Text, DecimalType], Text, type) -> None
        """
        :param to_nearest:
            The value that the filter should round to.

            E.g., ``Round(1)`` rounds to the nearest whole number.

            If you want to round to a float value, it is recommended
            that you provide it as a string or Decimal, to avoid
            floating point problems.

        :param rounding:
            Controls how to round values.

        :param result_type:
            The type of result to return.
        """
        super(Round, self).__init__()

        self.to_nearest = DecimalType(to_nearest)

        # Rounding to negative values isn't supported.
        # I'm not even sure if that concept is valid.
        Min(DecimalType('0')).apply(self.to_nearest)

        self.result_type    = result_type
        self.rounding       = rounding
sigproc.py 文件源码 项目:Speaker_recognition 作者: Mgajurel 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
rgba.py 文件源码 项目:macos-st-packages 作者: zce 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def round_int(dec):
    """Round float to nearest int using expected rounding."""

    return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))
st_scheme_template.py 文件源码 项目:macos-st-packages 作者: zce 项目源码 文件源码 阅读 25 收藏 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
lcv.py 文件源码 项目:lego-collection-value 作者: derekbrameyer 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def round_decimal(x):
    return Decimal(x).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
dynamo_sessions.py 文件源码 项目:sqs-browser-events 作者: ReutersMedia 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def quantize_tstamp(ts):
    return ts.quantize(decimal.Decimal('0.000001'),rounding=decimal.ROUND_HALF_UP)
tests.py 文件源码 项目:babar3 作者: Babaritech 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_balance_calcul(self):
        """
        Test balance is sum of payments minus sum of purchases
        """
        setup()
        amount = Decimal(200)
        Payment.objects.create(
            customer=Customer.objects.get(nickname="jim"),
            amount=amount
        )
        for i in range(25):
            if(random.choice((True, False))):
                Purchase.objects.create(
                    customer=Customer.objects.get(nickname="jim"),
                    product=Product.objects.get(name="Umbrella")
                )
                amount -= 5
            else:
                m = random.randrange(0, 20000) / 100
                Payment.objects.create(
                    customer=Customer.objects.get(nickname="jim"),
                    amount=m
                )
                amount += Decimal(m)
        self.assertEqual(
            Customer.objects.get(nickname="jim").balance,
            amount.quantize(Decimal('.001'), rounding=ROUND_HALF_UP)
        )
preprocessing.py 文件源码 项目:sbrt2017 作者: igormq 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'),
                                                rounding=decimal.ROUND_HALF_UP
                                                ))
sigproc.py 文件源码 项目:DTW_physionet2016 作者: JJGO 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
sigproc.py 文件源码 项目:DTW_physionet2016 作者: JJGO 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
ocds.py 文件源码 项目:openregistry.api 作者: openprocurement 项目源码 文件源码 阅读 88 收藏 0 点赞 0 评论 0
def to_native(self, value, context=None):
        try:
            value = Decimal(value).quantize(self.precision, rounding=ROUND_HALF_UP).normalize()
        except (TypeError, InvalidOperation):
            raise ConversionError(self.messages['number_coerce'].format(value))

        if self.min_value is not None and value < self.min_value:
            raise ConversionError(self.messages['number_min'].format(value))
        if self.max_value is not None and self.max_value < value:
            raise ConversionError(self.messages['number_max'].format(value))

        return value
advanced_box_score_deserializer_utils.py 文件源码 项目:nba_data 作者: jaebradley 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def parse_float(float_value):
        if float_value is None:
            return AdvancedBoxScoreDeserializerUtils.default_decimal_value

        if not isinstance(float_value, float):
            raise ValueError("Expected a float instead of %s", float_value)

        return Decimal(Decimal(float_value).quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
advanced_box_score_deserializer_utils.py 文件源码 项目:nba_data 作者: jaebradley 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def parse_percentage(percentage):
        if percentage is None:
            return AdvancedBoxScoreDeserializerUtils.default_decimal_value

        if not isinstance(percentage, float):
            raise ValueError("Expected a float instead of %s", percentage)

        return Decimal((100 * Decimal(percentage)).quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
utils.py 文件源码 项目:discord_chat_bot 作者: chromaticity 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def sane_round_int(x):
    return int(decimal.Decimal(x).quantize(1, rounding=decimal.ROUND_HALF_UP))
make_screenshots.py 文件源码 项目:biweeklybudget 作者: jantman 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _add_transactions(self, data_sess, pp):
        budgets = list(data_sess.query(Budget).filter(
            Budget.is_active.__eq__(True),
            Budget.is_income.__eq__(False),
            Budget.is_periodic.__eq__(True)
        ).all())
        target = 1950
        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=randrange(0, 12)),
                description='Transaction %d' % count
            ))
            data_sess.flush()
            data_sess.commit()
_compat.py 文件源码 项目:Infrax-as-Code-1000-webservers-in-40-minutes 作者: ezeeetm 项目源码 文件源码 阅读 23 收藏 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)
spreadsheet_formula.py 文件源码 项目:transformer 作者: zapier 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def func_round(a, places=0):
    """ functor for rounding using standard rules """
    return Decimal(a).quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP)
rds.py 文件源码 项目:cloud-custodian 作者: capitalone 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def process(self, resources):
        c = local_session(self.manager.session_factory).client('rds')
        for r in resources:
            old_val = D(r['AllocatedStorage'])
            _100 = D(100)
            new_val = ((_100 + D(self.data['percent'])) / _100) * old_val
            rounded = int(new_val.quantize(D('0'), ROUND_HALF_UP))
            c.modify_db_instance(
                DBInstanceIdentifier=r['DBInstanceIdentifier'],
                AllocatedStorage=rounded,
                ApplyImmediately=self.data.get('immediate', False))
rgba.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def round_int(dec):
    """Round float to nearest int using expected rounding."""

    return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))


问题


面经


文章

微信
公众号

扫码关注公众号