當前位置: 首頁>>代碼示例>>Python>>正文


Python decimal.localcontext方法代碼示例

本文整理匯總了Python中decimal.localcontext方法的典型用法代碼示例。如果您正苦於以下問題:Python decimal.localcontext方法的具體用法?Python decimal.localcontext怎麽用?Python decimal.localcontext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在decimal的用法示例。


在下文中一共展示了decimal.localcontext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: float2dec

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:secnot,項目名稱:rectpack,代碼行數:21,代碼來源:packer.py

示例2: number_to_string

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:seperman,項目名稱:deepdiff,代碼行數:25,代碼來源:helper.py

示例3: test_decimal_precision

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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)) 
開發者ID:amzn,項目名稱:ion-python,代碼行數:19,代碼來源:test_decimal.py

示例4: _serialize_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:amzn,項目名稱:ion-python,代碼行數:21,代碼來源:writer_binary_raw.py

示例5: _parse_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:amzn,項目名稱:ion-python,代碼行數:20,代碼來源:reader_binary.py

示例6: from_wei

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:ethereum,項目名稱:eth-utils,代碼行數:25,代碼來源:currency.py

示例7: convert_metric

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:paperswithcode,項目名稱:axcell,代碼行數:25,代碼來源:bm25_naive.py

示例8: integer_squareroot

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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()) 
開發者ID:ethereum,項目名稱:py-evm,代碼行數:22,代碼來源:numeric.py

示例9: scale_places

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:FISCO-BCOS,項目名稱:python-sdk,代碼行數:27,代碼來源:numeric.py

示例10: _format_data

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:openstack,項目名稱:cloudkitty,代碼行數:26,代碼來源:prometheus.py

示例11: convert_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:Yelp,項目名稱:clusterman,代碼行數:18,代碼來源:misc.py

示例12: format_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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)) 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:18,代碼來源:__init__.py

示例13: scale_places

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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 
開發者ID:ethereum,項目名稱:eth-abi,代碼行數:26,代碼來源:numeric.py

示例14: test_asyncio_task_decimal_context

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
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') 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:24,代碼來源:test_context.py

示例15: um2mm

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import localcontext [as 別名]
def um2mm(length: Decimal, prec: int) -> Decimal:
    """
    Convert a length in microns to millimeters with rounding.

    :param length: The input length in microns
    :param prec: The number of digits after the decimal place to use
    :return: A length in millimeters
    """
    with decimal.localcontext() as c:
        c.rounding = decimal.ROUND_HALF_UP
        mm = length/Decimal(1000)
        p = c.power(10, prec)
        # I would use .quantize(...) here, but it doesn't seem to work for quantization values > 1 (only 1, .1, .01, ...)
        return (mm*p).to_integral_exact()/p 
開發者ID:ucb-bar,項目名稱:hammer,代碼行數:16,代碼來源:__init__.py


注:本文中的decimal.localcontext方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。