Python decimal 模块,ROUND_HALF_UP 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用decimal.ROUND_HALF_UP

项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
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)
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
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
项目:flask-zhenai-mongo-echarts    作者:Fretice    | 项目源码 | 文件源码
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)
项目:python-glareclient    作者:openstack    | 项目源码 | 文件源码
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()
项目:QRL    作者:theQRL    | 项目源码 | 文件源码
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)
项目:otRebuilder    作者:Pal3love    | 项目源码 | 文件源码
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)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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))
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def round_decimal(d: decimal.Decimal) -> decimal.Decimal:
    return decimal.Decimal(d).quantize(DECIMAL_QUANTIZE, decimal.ROUND_HALF_UP)
项目:eyeD3    作者:nicfit    | 项目源码 | 文件源码
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
项目:filters    作者:eflglobal    | 项目源码 | 文件源码
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
项目:Speaker_recognition    作者:Mgajurel    | 项目源码 | 文件源码
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
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))
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
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
项目:lego-collection-value    作者:derekbrameyer    | 项目源码 | 文件源码
def round_decimal(x):
    return Decimal(x).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
项目:sqs-browser-events    作者:ReutersMedia    | 项目源码 | 文件源码
def quantize_tstamp(ts):
    return ts.quantize(decimal.Decimal('0.000001'),rounding=decimal.ROUND_HALF_UP)
项目:babar3    作者:Babaritech    | 项目源码 | 文件源码
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)
        )
项目:sbrt2017    作者:igormq    | 项目源码 | 文件源码
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'),
                                                rounding=decimal.ROUND_HALF_UP
                                                ))
项目:DTW_physionet2016    作者:JJGO    | 项目源码 | 文件源码
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
项目:DTW_physionet2016    作者:JJGO    | 项目源码 | 文件源码
def round_half_up(number):
    return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
项目:openregistry.api    作者:openprocurement    | 项目源码 | 文件源码
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
项目:nba_data    作者:jaebradley    | 项目源码 | 文件源码
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))
项目:nba_data    作者:jaebradley    | 项目源码 | 文件源码
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))
项目:discord_chat_bot    作者:chromaticity    | 项目源码 | 文件源码
def sane_round_int(x):
    return int(decimal.Decimal(x).quantize(1, rounding=decimal.ROUND_HALF_UP))
项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
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()
项目:Infrax-as-Code-1000-webservers-in-40-minutes    作者:ezeeetm    | 项目源码 | 文件源码
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)
项目:transformer    作者:zapier    | 项目源码 | 文件源码
def func_round(a, places=0):
    """ functor for rounding using standard rules """
    return Decimal(a).quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP)
项目:cloud-custodian    作者:capitalone    | 项目源码 | 文件源码
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))
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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))
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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
项目:aio    作者:pavhofman    | 项目源码 | 文件源码
def roundToInt(timePos: float) -> int:
    return int(decimal.Decimal(timePos).quantize(decimal.Decimal(1),
                                                 rounding=decimal.ROUND_HALF_UP))
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
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
项目:py-money    作者:vimeo    | 项目源码 | 文件源码
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)
项目:minihydra    作者:VillanCh    | 项目源码 | 文件源码
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)
项目:dj-txmoney    作者:txerpa    | 项目源码 | 文件源码
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)
项目:dj-txmoney    作者:txerpa    | 项目源码 | 文件源码
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)
项目:wrf-python    作者:NCAR    | 项目源码 | 文件源码
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))
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
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)
项目:inwx-zonefile-sync    作者:lukas2511    | 项目源码 | 文件源码
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)
项目:yangson    作者:CZ-NIC    | 项目源码 | 文件源码
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')
项目:cohorts    作者:hammerlab    | 项目源码 | 文件源码
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)
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
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)
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
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)
项目:cvss    作者:skontar    | 项目源码 | 文件源码
def round_to_1_decimal(value):
    """
    Round to one decimal.
    """
    return value.quantize(D('0.1'), rounding=ROUND_HALF_UP)
项目:QRL    作者:theQRL    | 项目源码 | 文件源码
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)
项目:aws-greengrass-mini-fulfillment    作者:awslabs    | 项目源码 | 文件源码
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
项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
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
项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
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)