Пример #1
0
def test_add(f1, f2):
    s1, s2 = str(f1), str(f2)
    cd1, cd2 = cdecimal.Decimal(s1), cdecimal.Decimal(s2)
    d1, d2 = decimal.Decimal(s1), decimal.Decimal(s2)
    assert str(cd1) == s1
    assert str(cd2) == s2
    assert str(cd1 + cd2) == str(d1 + d2)
Пример #2
0
 def getdecimal(self,*mpaths):
     ''' like get, but return a decimal value. If value to return is None or not numeric, zero is returned.
         warning: this function might 'mask' errors, because when input is not-valid, it aalwyas return a decimal 0. 
         useful eg for when math calculations are needed in mapping.
     '''
     terug = self.get(*mpaths)
     if terug and terug[-1] == u'-':    #if minus-sign at the end, put it in front. This is useful for idocs, where fields are never defined as numeric.
         terug = terug[-1] + terug[:-1]
     try:
         return decimal.Decimal(terug)
     except (TypeError,ValueError):
         return decimal.Decimal('0')
Пример #3
0
def main():
    D_to_x = {}
    x_squared_minus_one_is_square = {}
    for D in xrange(2, 1000 + 1):
        D_decimal = cdecimal.Decimal(D)
        if D_decimal.sqrt().is_integer():
            continue
        x_squared_minus_one = D_decimal
        while True:
            #print x_squared_minus_one
            if x_squared_minus_one not in x_squared_minus_one_is_square:
                x_squared_minus_one_is_square[x_squared_minus_one] = (
                    x_squared_minus_one + 1).sqrt().is_integer()
            if x_squared_minus_one_is_square[x_squared_minus_one] and \
                ((x_squared_minus_one / D_decimal).sqrt().is_integer()):
                break
            x_squared_minus_one += D_decimal

        x = (x_squared_minus_one + 1).sqrt()
        print "D: %s, x: %s" % (D, x)
        D_to_x[D] = x

    import ipdb
    ipdb.set_trace()
    pass
Пример #4
0
def convert(t, convstr=True):
    """ t is the testset. At this stage the testset contains a tuple of
        operands t.op of various types. For decimal methods the first
        operand (self) is always converted to Decimal. If 'convstr' is
        true, string operands are converted as well.

        Context operands are of type deccheck.Context, rounding mode
        operands are given as a tuple (C.rounding, P.rounding).

        Other types (float, int, etc.) are left unchanged.
    """
    for i, op in enumerate(t.op):

        context.clear_status()

        if not t.contextfunc and i == 0 or \
           convstr and isinstance(op, str):
            try:
                c = C.Decimal(op)
                cex = None
            except (TypeError, ValueError, OverflowError) as e:
                c = None
                cex = e.__class__

            try:
                p = RestrictedDecimal(op)
                pex = None
            except (TypeError, ValueError, OverflowError) as e:
                p = None
                pex = e.__class__

            t.cop.append(c)
            t.cex.append(cex)
            t.pop.append(p)
            t.pex.append(pex)

            if cex is pex:
                if str(c) != str(p) or not context.assert_eq_status():
                    raise_error(t)
                if cex and pex:
                    # nothing to test
                    return 0
            else:
                raise_error(t)

        elif isinstance(op, Context):
            t.context = op
            t.cop.append(op.c)
            t.pop.append(op.p)

        elif op in RoundModes:
            t.cop.append(op[0])
            t.pop.append(op[1])

        else:
            t.cop.append(op)
            t.pop.append(op)

    return 1
Пример #5
0
def test_after():
    """Test that we can fetch the first rate after a missing rate."""
    d, e = store.get_rate('EUR',
                          'GBP',
                          as_of_date=datetime.date(2015, 10, 10),
                          closest_rate=ecbxrate.AFTER)

    assert d == datetime.date(2015, 10, 12)
    assert e == decimal.Decimal('0.740100')
Пример #6
0
def test_before():
    """Test that we can fetch the first rate before a missing rate."""
    d, e = store.get_rate('EUR',
                          'GBP',
                          as_of_date=datetime.date(2015, 10, 10),
                          closest_rate=ecbxrate.BEFORE)

    assert d == datetime.date(2015, 10, 9)
    assert e == decimal.Decimal('0.740700')
Пример #7
0
 def getcountsum(self, *mpaths):
     ''' return the sum for all values found in mpath. Eg total number of ordered quantities.'''
     mpath_for_found_node = mpaths[-1].copy()
     for key, value in list(mpaths[-1].items()):
         if value is None:
             del mpaths[-1][key]
     count = decimal.Decimal(0)
     for i in self.getloop(*mpaths):
         count += i.getdecimal(mpath_for_found_node)
     return str(count)
Пример #8
0
def test_historic_rate():
    """Test that we can fetch a particular historic rate."""
    d, e = store.get_rate('EUR', 'GBP', as_of_date=datetime.date(2015, 1, 8))

    assert d == datetime.date(2015, 1, 8)
    assert e == decimal.Decimal('0.781100')

    # The closest rate option should have no effect
    d, e = store.get_rate('EUR',
                          'GBP',
                          as_of_date=datetime.date(2015, 1, 8),
                          closest_rate=ecbxrate.BEFORE)

    assert d == datetime.date(2015, 1, 8)
    assert e == decimal.Decimal('0.781100')

    d, e = store.get_rate('EUR',
                          'GBP',
                          as_of_date=datetime.date(2015, 1, 8),
                          closest_rate=ecbxrate.AFTER)

    assert d == datetime.date(2015, 1, 8)
    assert e == decimal.Decimal('0.781100')
Пример #9
0
    def _parse_xml(self, xmlfile, days=None):
        rates = []
        date_count = 0
        current_date = None
        max_date = None

        for event, element in etree.iterparse(xmlfile,
                                              events=('start', 'end')):
            if element.tag != CUBE_TAG:
                continue

            if event == 'start' and element.tag == CUBE_TAG:
                time = element.get('time', None)
                if time:
                    m = _date_re.match(time)
                    current_date = datetime.date(int(m.group(1)),
                                                 int(m.group(2)),
                                                 int(m.group(3)))

                    if max_date is None or max_date < current_date:
                        max_date = current_date

                    if days and date_count + 1 > days:
                        break

                    date_count += 1

            if event == 'end' and element.tag == CUBE_TAG:
                currency = element.get('currency', None)
                rate = element.get('rate', None)

                if currency and rate:
                    rate = decimal.Decimal(rate)

                    rates.append({
                        'date': current_date,
                        'currency': currency,
                        'rate': rate
                    })

        return (rates, date_count, max_date)
Пример #10
0
print(
    "\n# ======================================================================"
)
print("#                               Factorial")
print(
    "# ======================================================================\n"
)

C.getcontext().prec = C.MAX_PREC

for n in [100000, 1000000, 10000000, 100000000]:

    print("n = %d\n" % n)

    start_calc = time.time()
    x = factorial(C.Decimal(n), 0)
    end_calc = time.time()
    start_conv = time.time()
    sx = str(x)
    end_conv = time.time()
    print("cdecimal:")
    print("calculation time: %fs" % (end_calc - start_calc))
    print("conversion time: %fs\n" % (end_conv - start_conv))

    start_calc = time.time()
    y = factorial(mpz(n), 0)
    end_calc = time.time()
    start_conv = time.time()
    sy = str(y)
    end_conv = time.time()
Пример #11
0
propose_decision_fee = 10**5
create_jury_fee = 10**4
jury_vote_fee = 500
reveal_jury_vote_fee = 500
SVD_consensus_fee = 0
buy_shares_fee = 10**5
collect_winnings_reward = 5 * 10**4
# Lower limits on what the "time" tag in a block can say.
mmm = 100
# Take the median of this many of the blocks.
# How far back in history do we look when we use statistics to guess at
# the current blocktime and difficulty.
history_length = 400
# This constant is selected such that the 50 most recent blocks count for 1/2 the
# total weight.
inflection = cdecimal.Decimal('0.985')
download_many = 50  # Max number of blocks to request from a peer at the same time.
max_download = 58000
#buy_shares_target='0'*4+'1'+'9'*59
buy_shares_target = '0' * 3 + '1' + '9' * 60
blocktime = 60
DB = {
    'reward_peers_queue': multiprocessing.Queue(),
    'suggested_blocks': multiprocessing.Queue(),
    'suggested_txs': multiprocessing.Queue(),
    'heart_queue': multiprocessing.Queue(),
}
#seconds_per_week=604800
#cycle_length=seconds_per_week/blocktime#cycle_length
cycle_length = 40
vote_reveal_length = cycle_length / 10
Пример #12
0
def python_test(num1, num2):
    x = cdecimal.Decimal(num1)
    y = cdecimal.Decimal(num2)
    return x * y
Пример #13
0
    def get_rate(self,
                 from_currency,
                 to_currency,
                 as_of_date=None,
                 closest_rate=False):
        """Returns the exchange rate pair (date, E), such that

                to_amount = from_amount * E

           where to_amount is expressed in to_currency and from_amount in
           from_currency.

           If ``as_of_date`` is specified, returns the rate published for the
           date specified.  You can also specify 'today' or 'yesterday' or
           'latest' for this parameter.

           If you specify a date and are happy with the latest rate known
           prior to that date, you can set ``closest_rate`` to BEFORE.  If
           you need instead the earliest rate known after that date, you can
           set ``closest_rate`` to AFTER.  For backwards compatibility,
           setting closest_rate to True will have the same effect as BEFORE.

           If no exchange rate is known for the combination you have
           specified, this method returns (date, None)."""

        if as_of_date is None or as_of_date == 'today':
            as_of_date = datetime.date.today()
        if as_of_date == 'yesterday':
            as_of_date = datetime.date.today() - datetime.timedelta(days=1)

        er1 = exchange_rates.alias()
        er2 = exchange_rates.alias()

        if from_currency == 'EUR':
            from_rate = decimal.Decimal(1)
            if to_currency == 'EUR':
                to_rate = decimal.Decimal(1)
                stmt = None
            else:
                stmt = select([er2.c.date.label('date'),
                               er2.c.rate.label('to_rate')]) \
                  .where(er2.c.currency==to_currency)
                er = er2
        else:
            if to_currency == 'EUR':
                to_rate = decimal.Decimal(1)
                stmt = select([er1.c.date.label('date'),
                               er1.c.rate.label('from_rate')]) \
                  .where(er1.c.currency==from_currency)
                er = er1
            else:
                stmt = select([er1.c.date.label('date'),
                               er1.c.rate.label('from_rate'),
                               er2.c.rate.label('to_rate')]) \
                    .where(and_(er1.c.date==er2.c.date,
                                er1.c.currency==from_currency,
                                er2.c.currency==to_currency))
                er = er1

        if stmt is not None:
            if closest_rate == AFTER:
                stmt = stmt.order_by(er.c.date.asc())
            else:
                stmt = stmt.order_by(er.c.date.desc())

            stmt = stmt.limit(1)

            if as_of_date != 'latest':
                if closest_rate == True or closest_rate == BEFORE:
                    stmt = stmt.where(er.c.date <= as_of_date)
                elif closest_rate == AFTER:
                    stmt = stmt.where(er.c.date >= as_of_date)
                else:
                    stmt = stmt.where(er.c.date == as_of_date)

            conn = self._connect()
            try:
                with conn.begin() as trans:
                    result = conn.execute(stmt).fetchone()

                    if result is None or result == (None, None, None):
                        return (as_of_date, None)

                    if from_currency != 'EUR':
                        from_rate = result['from_rate']
                    if to_currency != 'EUR':
                        to_rate = result['to_rate']

                    rate_date = result['date']
            finally:
                self._disconnect()
        else:
            rate_date = datetime.date.today()

        with decimal.localcontext() as ctx:
            rate = to_rate / from_rate

        # If we have fewer than 6dp, round to 6dp; if we have more than 6dp
        # and the number has significant figures to the left of the decimal
        # point, round to 6dp.  Otherwise, round to 6sf.
        exp = rate.as_tuple().exponent
        if exp > -6:
            q = decimal.Decimal('0.000001')
            rate = rate.quantize(q)
        elif exp < -6:
            adj = rate.adjusted()
            if adj < 0:
                q = decimal.Decimal((0, [1], adj - 5))
            else:
                q = decimal.Decimal((0, [1], -6))
            rate = rate.quantize(q)

        return (rate_date, rate)
Пример #14
0
 def process_result_value(self, value, dialect):
     if value is None:
         return None
     return decimal.Decimal(value) / 10**6
Пример #15
0
 def test_encodeCDecimal(self):
     sut = cdecimal.Decimal("1337.1337")
     encoded = ujson.encode(sut, double_precision=100)
     decoded = ujson.decode(encoded)
     self.assertEquals(decoded, 1337.1337)