Python decimal.localcontext() Examples

The following are 30 code examples of decimal.localcontext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module decimal , or try the search function .
Example #1
Source File: bm25_naive.py    From axcell with Apache License 2.0 7 votes vote down vote up
def convert_metric(raw_value, rng, complementary):
    format = "{x}"

    percentage = '%' in raw_value
    if percentage:
        format += '%'

    with localcontext() as ctx:
        ctx.traps[InvalidOperation] = 0
        parsed = extract_value(raw_value, format)
        parsed = MetricValue(parsed, '%' if percentage else None)

        if complementary:
            parsed = parsed.complement()
        if rng == '0-1':
            parsed = parsed.to_percentage() / 100
        elif rng == '1-100':
            parsed = parsed.to_percentage()
        elif rng == 'abs':
            parsed = parsed.to_absolute()
        else:
            parsed = parsed.to_unitless()
    return parsed 
Example #2
Source File: prometheus.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def _format_data(self, metric_name, scope_key, scope_id, start, end, data):
        """Formats Prometheus data format to Cloudkitty data format.

        Returns metadata, groupby, qty
        """
        metadata = {}
        for meta in self.conf[metric_name]['metadata']:
            metadata[meta] = data['metric'][meta]

        groupby = {scope_key: scope_id}
        for meta in self.conf[metric_name]['groupby']:
            groupby[meta] = data['metric'].get(meta, '')

        with localcontext() as ctx:
            ctx.prec = 9
            ctx.rounding = ROUND_HALF_UP

            qty = ck_utils.convert_unit(
                +Decimal(data['value'][1]),
                self.conf[metric_name]['factor'],
                self.conf[metric_name]['offset'],
            )

        return metadata, groupby, qty 
Example #3
Source File: numeric.py    From eth-abi with MIT License 6 votes vote down vote up
def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
    """
    Returns a function that shifts the decimal point of decimal values to the
    right by ``places`` places.
    """
    if not isinstance(places, int):
        raise ValueError(
            f'Argument `places` must be int.  Got value {places} of type {type(places)}.',
        )

    with decimal.localcontext(abi_decimal_context):
        scaling_factor = TEN ** -places

    def f(x: decimal.Decimal) -> decimal.Decimal:
        with decimal.localcontext(abi_decimal_context):
            return x * scaling_factor

    places_repr = f'Eneg{places}' if places > 0 else f'Epos{-places}'
    func_name = f'scale_by_{places_repr}'

    f.__name__ = func_name
    f.__qualname__ = func_name

    return f 
Example #4
Source File: packer.py    From rectpack with Apache License 2.0 6 votes vote down vote up
def float2dec(ft, decimal_digits):
    """
    Convert float (or int) to Decimal (rounding up) with the
    requested number of decimal digits.

    Arguments:
        ft (float, int): Number to convert
        decimal (int): Number of digits after decimal point

    Return:
        Decimal: Number converted to decima
    """
    with decimal.localcontext() as ctx:
        ctx.rounding = decimal.ROUND_UP
        places = decimal.Decimal(10)**(-decimal_digits)
        return decimal.Decimal.from_float(float(ft)).quantize(places)


# Sorting algos for rectangle lists 
Example #5
Source File: helper.py    From deepdiff with MIT License 6 votes vote down vote up
def number_to_string(number, significant_digits, number_format_notation="f"):
    """
    Convert numbers to string considering significant digits.
    """
    try:
        using = number_formatting[number_format_notation]
    except KeyError:
        raise ValueError("number_format_notation got invalid value of {}. The valid values are 'f' and 'e'".format(number_format_notation)) from None
    if isinstance(number, Decimal):
        tup = number.as_tuple()
        with localcontext() as ctx:
            ctx.prec = len(tup.digits) + tup.exponent + significant_digits
            number = number.quantize(Decimal('0.' + '0' * significant_digits))
    elif not isinstance(number, numbers):
        return number
    result = (using % significant_digits).format(number)
    # Special case for 0: "-0.00" should compare equal to "0.00"
    if set(result) <= ZERO_DECIMAL_CHARACTERS:
        result = "0.00"
    # https://bugs.python.org/issue36622
    if number_format_notation == 'e' and isinstance(number, float):
        result = result.replace('+0', '+')
    return result 
Example #6
Source File: writer_binary_raw.py    From ion-python with Apache License 2.0 6 votes vote down vote up
def _serialize_decimal(ion_event):
    buf = bytearray()
    value = ion_event.value
    validate_scalar_value(value, Decimal)
    sign, digits, exponent = value.as_tuple()
    with localcontext() as context:
        # Adjusting precision for taking into account arbitrarily large/small
        # numbers
        context.prec = len(digits)
        coefficient = int(value.scaleb(-exponent).to_integral_value())
    if not sign and not exponent and not coefficient:
        # The value is 0d0; other forms of zero will fall through.
        buf.append(_Zeros.DECIMAL)
    else:
        value_buf = bytearray()
        length = _write_decimal_value(value_buf, exponent, coefficient, sign)
        _write_length(buf, length, _TypeIds.DECIMAL)
        buf.extend(value_buf)
    return buf 
Example #7
Source File: test_context.py    From android_universal with MIT License 6 votes vote down vote up
def test_asyncio_task_decimal_context(self):
        async def fractions(t, precision, x, y):
            with decimal.localcontext() as ctx:
                ctx.prec = precision
                a = decimal.Decimal(x) / decimal.Decimal(y)
                await asyncio.sleep(t)
                b = decimal.Decimal(x) / decimal.Decimal(y ** 2)
                return a, b

        async def main():
            r1, r2 = await asyncio.gather(
                fractions(0.1, 3, 1, 3), fractions(0.2, 6, 1, 3))

            return r1, r2

        r1, r2 = asyncio.run(main())

        self.assertEqual(str(r1[0]), '0.333')
        self.assertEqual(str(r1[1]), '0.111')

        self.assertEqual(str(r2[0]), '0.333333')
        self.assertEqual(str(r2[1]), '0.111111') 
Example #8
Source File: test_decimal.py    From ion-python with Apache License 2.0 6 votes vote down vote up
def test_decimal_precision():
    from decimal import localcontext

    with localcontext() as ctx:
        # ensure test executes with the default precision
        # (see https://docs.python.org/3.7/library/decimal.html#decimal.DefaultContext):
        ctx.prec = 28

        # decimal with 29 digits
        decimal = Decimal('1234567890123456789012345678.9')
        assert decimal == loads(dumps(decimal))
        assert decimal == loads(dumps(decimal, binary=False))

        # negative decimal with 29 digits
        decimal = Decimal('-1234567890123456789012345678.9')
        assert decimal == loads(dumps(decimal))
        assert decimal == loads(dumps(decimal, binary=False)) 
Example #9
Source File: reader_binary.py    From ion-python with Apache License 2.0 6 votes vote down vote up
def _parse_decimal(buf):
    """Parses the remainder of a file-like object as a decimal."""
    from decimal import localcontext
    exponent = _parse_var_int(buf, signed=True)
    sign_bit, coefficient = _parse_signed_int_components(buf)

    if coefficient == 0:
        # Handle the zero cases--especially negative zero
        value = Decimal((sign_bit, (0,), exponent))
    else:
        coefficient *= sign_bit and -1 or 1
        with localcontext() as context:
            # Adjusting precision for taking into account arbitrarily
            # large/small numbers
            context.prec = len(str(coefficient))
            value = Decimal(coefficient).scaleb(exponent)

    return value 
Example #10
Source File: currency.py    From eth-utils with MIT License 6 votes vote down vote up
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
    """
    Takes a number of wei and converts it to any other ether unit.
    """
    if unit.lower() not in units:
        raise ValueError(
            "Unknown unit.  Must be one of {0}".format("/".join(units.keys()))
        )

    if number == 0:
        return 0

    if number < MIN_WEI or number > MAX_WEI:
        raise ValueError("value must be between 1 and 2**256 - 1")

    unit_value = units[unit.lower()]

    with localcontext() as ctx:
        ctx.prec = 999
        d_number = decimal.Decimal(value=number, context=ctx)
        result_value = d_number / unit_value

    return result_value 
Example #11
Source File: __init__.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def format_decimal(n):
    """
    Convert the given float to a string without scientific notation
    """
    try:
        with decimal.localcontext() as ctx:
            ctx.prec = 7
            if isinstance(n, float):
                d = ctx.create_decimal(repr(n))
                return format(d.normalize(), 'f')
            elif isinstance(n, decimal.Decimal):
                return format(n.normalize(), 'f')
            else:
                return str(n)
    except Exception as e:
        logging.getLogger().error(str(e)) 
Example #12
Source File: numeric.py    From py-evm with MIT License 6 votes vote down vote up
def integer_squareroot(value: int) -> int:
    """
    Return the integer square root of ``value``.

    Uses Python's decimal module to compute the square root of ``value`` with
    a precision of 128-bits. The value 128 is chosen since the largest square
    root of a 256-bit integer is a 128-bit integer.
    """
    if not isinstance(value, int) or isinstance(value, bool):
        raise ValueError(
            f"Value must be an integer: Got: {type(value)}"
        )
    if value < 0:
        raise ValueError(
            f"Value cannot be negative: Got: {value}"
        )

    with decimal.localcontext() as ctx:
        ctx.prec = 128
        return int(decimal.Decimal(value).sqrt()) 
Example #13
Source File: currency.py    From python-sdk with MIT License 6 votes vote down vote up
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
    """
    Takes a number of wei and converts it to any other ether unit.
    """
    if unit.lower() not in units:
        raise ValueError(
            "Unknown unit.  Must be one of {0}".format("/".join(units.keys()))
        )

    if number == 0:
        return 0

    if number < MIN_WEI or number > MAX_WEI:
        raise ValueError("value must be between 1 and 2**256 - 1")

    unit_value = units[unit.lower()]

    with localcontext() as ctx:
        ctx.prec = 999
        d_number = decimal.Decimal(value=number, context=ctx)
        result_value = d_number / unit_value

    return result_value 
Example #14
Source File: numeric.py    From python-sdk with MIT License 6 votes vote down vote up
def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
    """
    Returns a function that shifts the decimal point of decimal values to the
    right by ``places`` places.
    """
    if not isinstance(places, int):
        raise ValueError(
            'Argument `places` must be int.  Got value {} of type {}.'.
            format(places, type(places)),
        )

    with decimal.localcontext(abi_decimal_context):
        scaling_factor = TEN ** -places

    def f(x: decimal.Decimal) -> decimal.Decimal:
        with decimal.localcontext(abi_decimal_context):
            return x * scaling_factor

    places_repr = 'Eneg{}'.format(places) if places > 0 else 'Epos{}'.format(-places)
    func_name = 'scale_by_{}'.format(places_repr)

    f.__name__ = func_name
    f.__qualname__ = func_name

    return f 
Example #15
Source File: misc.py    From clusterman with Apache License 2.0 6 votes vote down vote up
def convert_decimal(numeric):
    full_decimal = Decimal(numeric)
    _, digits, exponent = full_decimal.as_tuple()
    # Round to MAX_DECIMAL_PLACES, if result has more places than that.
    if exponent < -MAX_DECIMAL_PLACES:
        # quantize can raise `decimal.InvalidOperation` if result is greater
        # than context precision, which is 28 by default. to get around this,
        # temporarily set a new precision up to the max number of sig figs  of
        # `full_decimal`, which is also the max for the result of `quantize`.
        # this ensures that the result of `quantize` will be within the precision
        # limit, and not raise the error.
        with localcontext() as ctx:
            ctx.prec = max(len(digits), getcontext().prec)
            return full_decimal.quantize(_PLACES_VALUE, rounding=ROUND_HALF_UP)
    else:
        return full_decimal 
Example #16
Source File: decoding.py    From eth-abi with MIT License 5 votes vote down vote up
def decoder_fn(self, data):
        value = big_endian_to_int(data)

        with decimal.localcontext(abi_decimal_context):
            decimal_value = decimal.Decimal(value) / TEN ** self.frac_places

        return decimal_value 
Example #17
Source File: utils.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decimal_to_twoval1(val1, val2=None):
    with decimal.localcontext() as ctx:
        ctx.prec = _enough_decimal_places
        d = decimal.Decimal(val1)
        i = round(d)
        f = d - i
    return float(i), float(f) 
Example #18
Source File: test_precision.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_two_sum_simple():
    with decimal.localcontext(decimal.Context(prec=40)):
        i, f = 65536, 3.637978807091714e-12
        a = Decimal(i) + Decimal(f)
        s, r = two_sum(i, f)
        b = Decimal(s) + Decimal(r)
        assert (abs(a-b)*u.day).to(u.ns) < 1*u.ns 
Example #19
Source File: utils.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def twoval_to_decimal1(val1, val2):
    with decimal.localcontext() as ctx:
        ctx.prec = _enough_decimal_places
        return decimal.Decimal(val1) + decimal.Decimal(val2) 
Example #20
Source File: numeric.py    From eth-abi with MIT License 5 votes vote down vote up
def compute_signed_fixed_bounds(
    num_bits: int,
    frac_places: int,
) -> Tuple[decimal.Decimal, decimal.Decimal]:
    int_lower, int_upper = compute_signed_integer_bounds(num_bits)

    with decimal.localcontext(abi_decimal_context):
        exp = TEN ** -frac_places
        lower = decimal.Decimal(int_lower) * exp
        upper = decimal.Decimal(int_upper) * exp

    return lower, upper 
Example #21
Source File: test_basic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_decimal_context_does_not_affect_string(self, fmt):
        t = Time('2001', format='jyear', scale='tai')
        t.format = fmt
        with localcontext() as ctx:
            ctx.prec = 2
            t_s_2 = t.to_value(fmt, "str")
        t2 = Time('2001', format='jyear', scale='tai')
        t2.format = fmt
        with localcontext() as ctx:
            ctx.prec = 40
            t2_s_40 = t.to_value(fmt, "str")
        assert t_s_2 == t2_s_40, "String representation should not depend on Decimal context" 
Example #22
Source File: photometry.py    From astrocats with MIT License 5 votes vote down vote up
def set_pd_mag_from_flux_density(photodict,
                                 fd='',
                                 efd='',
                                 lefd='',
                                 uefd='',
                                 sig=DEFAULT_UL_SIGMA):
    """Set photometry dictionary from a flux density measurement.

    `fd` is assumed to be in microjanskys.
    """
    with localcontext() as ctx:
        if lefd == '' or uefd == '':
            lefd = efd
            uefd = efd
        prec = max(
            get_sig_digits(str(fd), strip_zeroes=False),
            get_sig_digits(str(lefd), strip_zeroes=False),
            get_sig_digits(str(uefd), strip_zeroes=False)) + 1
        ctx.prec = prec
        dlefd = Decimal(str(lefd))
        duefd = Decimal(str(uefd))
        if fd != '':
            dfd = Decimal(str(fd))
        dsig = Decimal(str(sig))
        if fd == '' or float(fd) < DEFAULT_UL_SIGMA * float(uefd):
            photodict[PHOTOMETRY.UPPER_LIMIT] = True
            photodict[PHOTOMETRY.UPPER_LIMIT_SIGMA] = str(sig)
            photodict[PHOTOMETRY.MAGNITUDE] = str(Decimal('23.9') - D25 * (
                dsig * duefd).log10())
            if fd:
                photodict[PHOTOMETRY.E_UPPER_MAGNITUDE] = str(D25 * (
                    (dfd + duefd).log10() - dfd.log10()))
        else:
            photodict[PHOTOMETRY.MAGNITUDE] = str(Decimal('23.9') - D25 *
                                                  dfd.log10())
            photodict[PHOTOMETRY.E_UPPER_MAGNITUDE] = str(D25 * (
                (dfd + duefd).log10() - dfd.log10()))
            photodict[PHOTOMETRY.E_LOWER_MAGNITUDE] = str(D25 * (
                dfd.log10() - (dfd - dlefd).log10())) 
Example #23
Source File: photometry.py    From astrocats with MIT License 5 votes vote down vote up
def set_pd_mag_from_counts(photodict,
                           c='',
                           ec='',
                           lec='',
                           uec='',
                           zp=DEFAULT_ZP,
                           sig=DEFAULT_UL_SIGMA):
    """Set photometry dictionary from a counts measurement."""
    with localcontext() as ctx:
        if lec == '' or uec == '':
            lec = ec
            uec = ec
        prec = max(
            get_sig_digits(str(c), strip_zeroes=False),
            get_sig_digits(str(lec), strip_zeroes=False),
            get_sig_digits(str(uec), strip_zeroes=False)) + 1
        ctx.prec = prec
        dlec = Decimal(str(lec))
        duec = Decimal(str(uec))
        if c != '':
            dc = Decimal(str(c))
        dzp = Decimal(str(zp))
        dsig = Decimal(str(sig))
        photodict[PHOTOMETRY.ZERO_POINT] = str(zp)
        if c == '' or float(c) < float(sig) * float(uec):
            photodict[PHOTOMETRY.UPPER_LIMIT] = True
            photodict[PHOTOMETRY.UPPER_LIMIT_SIGMA] = str(sig)
            photodict[PHOTOMETRY.MAGNITUDE] = str(dzp - (D25 * (dsig * duec
                                                                ).log10()))
            dnec = Decimal('10.0') ** (
                (dzp - Decimal(photodict[PHOTOMETRY.MAGNITUDE])) / D25)
            photodict[PHOTOMETRY.E_UPPER_MAGNITUDE] = str(D25 * (
                (dnec + duec).log10() - dnec.log10()))
        else:
            photodict[PHOTOMETRY.MAGNITUDE] = str(dzp - D25 * dc.log10())
            photodict[PHOTOMETRY.E_UPPER_MAGNITUDE] = str(D25 * (
                (dc + duec).log10() - dc.log10()))
            photodict[PHOTOMETRY.E_LOWER_MAGNITUDE] = str(D25 * (
                dc.log10() - (dc - dlec).log10())) 
Example #24
Source File: numeric.py    From trinity with MIT License 5 votes vote down vote up
def integer_squareroot(value: int) -> int:
    """
    Return the integer square root of ``value``.
    Uses Python's decimal module to compute the square root of ``value`` with
    a precision of 128-bits. The value 128 is chosen since the largest square
    root of a 256-bit integer is a 128-bit integer.
    """
    if not isinstance(value, int) or isinstance(value, bool):
        raise ValueError("Value must be an integer: Got: {0}".format(type(value)))
    if value < 0:
        raise ValueError("Value cannot be negative: Got: {0}".format(value))

    with decimal.localcontext() as ctx:
        ctx.prec = 128
        return int(decimal.Decimal(value).sqrt()) 
Example #25
Source File: encoding.py    From eth-abi with MIT License 5 votes vote down vote up
def encode_fn(self, value):
        with decimal.localcontext(abi_decimal_context):
            scaled_value = value * TEN ** self.frac_places
            integer_value = int(scaled_value)

        return int_to_big_endian(integer_value) 
Example #26
Source File: test_statistics.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_decimal_basiccontext_mismatched_infs_to_nan(self):
        # Test adding Decimal INFs with opposite sign raises InvalidOperation.
        inf = Decimal('inf')
        data = [1, 2, inf, 3, -inf, 4]
        with decimal.localcontext(decimal.BasicContext):
            self.assertRaises(decimal.InvalidOperation, statistics._sum, data) 
Example #27
Source File: test_statistics.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_decimal_extendedcontext_mismatched_infs_to_nan(self):
        # Test adding Decimal INFs with opposite sign returns NAN.
        inf = Decimal('inf')
        data = [1, 2, inf, 3, -inf, 4]
        with decimal.localcontext(decimal.ExtendedContext):
            self.assertTrue(math.isnan(statistics._sum(data)[1])) 
Example #28
Source File: test_statistics.py    From android_universal with MIT License 5 votes vote down vote up
def test_decimal_basiccontext_mismatched_infs_to_nan(self):
        # Test adding Decimal INFs with opposite sign raises InvalidOperation.
        inf = Decimal('inf')
        data = [1, 2, inf, 3, -inf, 4]
        with decimal.localcontext(decimal.BasicContext):
            self.assertRaises(decimal.InvalidOperation, statistics._sum, data) 
Example #29
Source File: encoding.py    From eth-abi with MIT License 5 votes vote down vote up
def encode_fn(self, value):
        with decimal.localcontext(abi_decimal_context):
            scaled_value = value * TEN ** self.frac_places
            integer_value = int(scaled_value)

        unsigned_integer_value = integer_value % (2 ** self.value_bit_size)

        return int_to_big_endian(unsigned_integer_value) 
Example #30
Source File: test_floatformat.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_low_decimal_precision(self):
        """
        #15789
        """
        with localcontext() as ctx:
            ctx.prec = 2
            self.assertEqual(floatformat(1.2345, 2), '1.23')
            self.assertEqual(floatformat(15.2042, -3), '15.204')
            self.assertEqual(floatformat(1.2345, '2'), '1.23')
            self.assertEqual(floatformat(15.2042, '-3'), '15.204')
            self.assertEqual(floatformat(Decimal('1.2345'), 2), '1.23')
            self.assertEqual(floatformat(Decimal('15.2042'), -3), '15.204')