Ejemplo n.º 1
0
def test_decimal():
    if sys.version_info >= (3, ):
        # Check whether the _decimal package was built successfully
        import _decimal as decimal
    else:
        import decimal
    decimal.getcontext().prec = 6
    print("1/7 =", decimal.Decimal(1) / decimal.Decimal(7))
    decimal.getcontext().prec = 40
    print("1/7 =", decimal.Decimal(1) / decimal.Decimal(7))
Ejemplo n.º 2
0
def fuzz():
    with open(sys.argv[1], errors="surrogateescape") as fp:
        data = fp.read()
    try:
        dp = decimal_py.Decimal(data)
        dc = decimal_c.Decimal(data)
    except ValueError:
        return
    except ZeroDivisionError:
        return
    except (decimal_py.InvalidOperation, decimal_c.InvalidOperation):
        return
    assert repr(dp) == repr(dc)
    assert dp.is_canonical() == dc.is_canonical()
    assert dp.is_finite() == dc.is_finite()
    assert dp.is_infinite() == dc.is_infinite()
    assert dp.is_nan() == dc.is_nan()
    assert dp.is_normal() == dc.is_normal()
    assert dp.is_snan() == dc.is_snan()
    assert dp.is_qnan() == dc.is_qnan()
    assert dp.is_signed() == dc.is_signed()
    assert dp.is_subnormal() == dc.is_subnormal()
    assert dp.is_zero() == dc.is_zero()
    try:
        assert repr(dp + dp) == repr(dc + dc)
        assert repr(dp - dp) == repr(dc - dc)
        assert repr(dp * dp) == repr(dc * dc)
        assert repr(dp.adjusted()) == repr(dc.adjusted())
        assert repr(dp.as_tuple()) == repr(dc.as_tuple())
        assert repr(dp.canonical()) == repr(dc.canonical())
        assert repr(dp.compare(dp)) == repr(dc.compare(dc))
        assert repr(dp.conjugate()) == repr(dc.conjugate())
        assert repr(dp.copy_abs()) == repr(dc.copy_abs())
        assert repr(dp.copy_negate()) == repr(dc.copy_negate())
        assert repr(dp.copy_sign(dp)) == repr(dc.copy_sign(dc))
        assert repr(dp.exp()) == repr(dc.exp())
        assert repr(dp.fma(1, 1)) == repr(dc.fma(1, 1))
        assert repr(dp.ln()) == repr(dc.ln())
        assert repr(dp.log10()) == repr(dc.log10())
        assert repr(dp.logb()) == repr(dc.logb())
        assert repr(dp.logical_and(dp)) == repr(dc.logical_and(dc))
        assert repr(dp.logical_invert()) == repr(dc.logical_invert())
        assert repr(dp.logical_or(dp)) == repr(dc.logical_or(dc))
        assert repr(dp.logical_xor(dp)) == repr(dc.logical_xor(dc))
        assert repr(dp.max(dp)) == repr(dc.max(dc))
        assert repr(dp.max_mag(dp)) == repr(dc.max_mag(dc))
        assert repr(dp.min(dp)) == repr(dc.min(dc))
        assert repr(dp.min_mag(dp)) == repr(dc.min_mag(dc))
        assert repr(dp.next_minus()) == repr(dc.next_minus())
        assert repr(dp.next_plus()) == repr(dc.next_plus())
        assert repr(dp.next_toward(dp)) == repr(dc.next_toward(dc))
        assert repr(dp.normalize()) == repr(dc.normalize())
        assert repr(dp.number_class()) == repr(dc.number_class())
        assert repr(dp.quantize(dp)) == repr(dc.quantize(dc))
        assert repr(dp.radix()) == repr(dc.radix())
        assert repr(dp.remainder_near(dp)) == repr(dc.remainder_near(dc))
        assert repr(dp.rotate(dp)) == repr(dc.rotate(dc))
        assert repr(dp.same_quantum(dp)) == repr(dc.same_quantum(dc))
        assert repr(dp.scaleb(dp)) == repr(dc.scaleb(dc))
        assert repr(dp.shift(dp)) == repr(dc.shift(dc))
        assert repr(dp.sqrt()) == repr(dc.sqrt())
        assert repr(dp.to_eng_string()) == repr(dc.to_eng_string())
        assert repr(dp.to_integral()) == repr(dc.to_integral())
        assert repr(dp.to_integral_exact()) == repr(dc.to_integral_exact())
        assert repr(dp.to_integral_value()) == repr(dc.to_integral_value())
        try:
            assert repr(dp.as_integer_ratio()) == repr(dc.as_integer_ratio())
            assert repr(round(dp, 1)) == repr(round(dc, 1))
            assert repr(float(dp)) == repr(float(dc))
            assert repr(int(dp)) == repr(int(dc))
            assert repr(math.floor(dp)) == repr(math.floor(dc))
            assert repr(math.ceil(dp)) == repr(math.ceil(dc))
        except OverflowError:
            pass
        except ValueError:
            pass
    except decimal_py.DecimalException:
        pass
Ejemplo n.º 3
0
def as_dict(o):
    return c_as_dict(o)


def as_tuple(o):
    return c_as_tuple(o)


c_constants = {
    # c_as_name(c_as_unicode('true')): True,
    # c_as_name(c_as_unicode('false')): False,
    # c_as_name(c_as_unicode('null')): None,
    c_as_name(c_as_unicode('NaN')):
    float('nan'),
    c_as_name(c_as_unicode('NaND')):
    _decimal.Decimal(float('nan')),
    c_as_name(c_as_unicode('Inf')):
    float('inf'),
    c_as_name(c_as_unicode('NegInf')):
    float('-inf'),
}

reserved_name_dict = {'null': None, 'true': True, 'false': False}
empty_odict = OrderedDict([])
empty_list = []

#
# Readonly dict
#
# class rdict(dict):
#     #
Ejemplo n.º 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()
        t.maxcontext.clear_flags()

        if op in RoundModes:
            t.cop.append(op)
            t.pop.append(op)
            t.maxop.append(op)

        elif 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__

            try:
                C.setcontext(t.maxcontext)
                maxop = C.Decimal(op)
                maxex = None
            except (TypeError, ValueError, OverflowError) as e:
                maxop = None
                maxex = e.__class__
            finally:
                C.setcontext(context.c)

            t.cop.append(c)
            t.cex.append(cex)

            t.pop.append(p)
            t.pex.append(pex)

            t.maxop.append(maxop)
            t.maxex.append(maxex)

            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)

            # The exceptions in the maxcontext operation can legitimately
            # differ, only test that maxex implies cex:
            if maxex is not None and cex is not maxex:
                raise_error(t)

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

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

    return 1
Ejemplo n.º 5
0
print("# ======================================================================\n")

if C is not None:
    c = C.getcontext()
    c.prec = C.MAX_PREC
    c.Emax = C.MAX_EMAX
    c.Emin = C.MIN_EMIN

for n in [100000, 1000000]:

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

    if C is not None:
        # C version of decimal
        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))

    # Python integers
    start_calc = time.time()
    y = factorial(n, 0)
    end_calc = time.time()
    start_conv = time.time()
    sy = str(y)
    end_conv =  time.time()