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


Python decimal.getcontext方法代碼示例

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


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

示例1: test_arith_series_with_array

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def test_arith_series_with_array(self, data, all_arithmetic_operators):
        op_name = all_arithmetic_operators
        s = pd.Series(data)

        context = decimal.getcontext()
        divbyzerotrap = context.traps[decimal.DivisionByZero]
        invalidoptrap = context.traps[decimal.InvalidOperation]
        context.traps[decimal.DivisionByZero] = 0
        context.traps[decimal.InvalidOperation] = 0

        # Decimal supports ops with int, but not float
        other = pd.Series([int(d * 100) for d in data])
        self.check_opname(s, op_name, other)

        if "mod" not in op_name:
            self.check_opname(s, op_name, s * 2)

        self.check_opname(s, op_name, 0)
        self.check_opname(s, op_name, 5)
        context.traps[decimal.DivisionByZero] = divbyzerotrap
        context.traps[decimal.InvalidOperation] = invalidoptrap 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_decimal.py

示例2: format_number

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def format_number(value, max_digits, decimal_places):
    """
    Formats a number into a string with the requisite number of digits and
    decimal places.
    """
    if value is None:
        return None
    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        if max_digits is not None:
            context.prec = max_digits
        if decimal_places is not None:
            value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
        else:
            context.traps[decimal.Rounded] = 1
            value = context.create_decimal(value)
        return "{:f}".format(value)
    if decimal_places is not None:
        return "%.*f" % (decimal_places, value)
    return "{:f}".format(value) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:22,代碼來源:utils.py

示例3: format_number

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def format_number(value, max_digits, decimal_places):
    """
    Format a number into a string with the requisite number of digits and
    decimal places.
    """
    if value is None:
        return None
    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        if max_digits is not None:
            context.prec = max_digits
        if decimal_places is not None:
            value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
        else:
            context.traps[decimal.Rounded] = 1
            value = context.create_decimal(value)
        return "{:f}".format(value)
    if decimal_places is not None:
        return "%.*f" % (decimal_places, value)
    return "{:f}".format(value) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:22,代碼來源:utils.py

示例4: format_number

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def format_number(value, max_digits, decimal_places):
    """
    Format a number into a string with the requisite number of digits and
    decimal places.
    """
    if value is None:
        return None
    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        if max_digits is not None:
            context.prec = max_digits
        if decimal_places is not None:
            value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
        else:
            context.traps[decimal.Rounded] = 1
            value = context.create_decimal(value)
        return "{:f}".format(value)
    if decimal_places is not None:
        return "%.*f" % (decimal_places, value)
    return "{:f}".format(value) 
開發者ID:PacktPublishing,項目名稱:Hands-On-Application-Development-with-PyCharm,代碼行數:22,代碼來源:utils.py

示例5: ArchPi

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def ArchPi(precision=99):
    # x: circumference of the circumscribed (outside) regular polygon
    # y: circumference of the inscribed (inside) regular polygon

    decimal.getcontext().prec = precision+1
    D=decimal.Decimal
    
    # max error allowed
    eps = D(1)/D(10**precision)
    
    # initialize w/ square
    x = D(4)
    y = D(2)*D(2).sqrt()

    ctr = D(0)
    while x-y > eps:
        xnew = 2*x*y/(x+y)
        y = D(xnew*y).sqrt()
        x = xnew
        ctr += 1
        

    return str((x+y)/D(2)) 
開發者ID:ActiveState,項目名稱:code,代碼行數:25,代碼來源:recipe-578478.py

示例6: convert_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [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

示例7: quantize

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def quantize(self, value):
        """
        Quantize the decimal value to the configured precision.
        """
        if self.decimal_places is None:
            return value

        context = decimal.getcontext().copy()
        if self.max_digits is not None:
            context.prec = self.max_digits
        return value.quantize(
            decimal.Decimal('.1') ** self.decimal_places,
            rounding=self.rounding,
            context=context
        )


# Date & time fields... 
開發者ID:BeanWei,項目名稱:Dailyfresh-B2C,代碼行數:20,代碼來源:fields.py

示例8: _dt_to_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def _dt_to_decimal(utc):
        """Datetime to Decimal.

        Some databases don't store microseconds in datetime
        so we always store as Decimal unixtime.
        """
        if utc is None:
            return None

        decimal.getcontext().prec = 30
        return (decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) +
                (decimal.Decimal(str(utc.microsecond)) /
                 decimal.Decimal("1000000.0"))) 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:15,代碼來源:sqlalchemy_types.py

示例9: _to_fixed

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def _to_fixed(value: Any) -> Decimal:
    if isinstance(value, float):
        raise TypeError("Cannot convert float to decimal - use a string instead")

    if isinstance(value, (str, bytes)):
        try:
            value = Wei(value)
        except TypeError:
            pass
    try:
        ctx = getcontext()
        ctx.prec = 100
        return Decimal(value, context=ctx)
    except Exception:
        raise TypeError(f"Cannot convert {type(value).__name__} '{value}' to decimal.") 
開發者ID:eth-brownie,項目名稱:brownie,代碼行數:17,代碼來源:datatypes.py

示例10: format_number

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def format_number(value, decimal_places):
    """
    Formats a number into a string with the requisite number of decimal places.
    """
    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        return '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
    else:
        return "%.*f" % (decimal_places, value) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:11,代碼來源:utils.py

示例11: __init__

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def __init__(self, context=None):
        self.context = context or decimal.getcontext() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:4,代碼來源:array.py

示例12: solution

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def solution(limit):
    decimal.getcontext().prec = 102  # more than 100 to avoid round errors
    result = 0
    for n in range(limit + 1):
        if not math.sqrt(n).is_integer():  # check if is irrational
            # sum digits
            result += sum(decimal.Decimal(n).sqrt().as_tuple()[1][:100])

    return result 
開發者ID:DestructHub,項目名稱:ProjectEuler,代碼行數:11,代碼來源:solution_1.py

示例13: convert_value

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def convert_value(cls, value, to, prec=33):
        """
        Convert values from/to pip/bip.
        Args:
            value (string|int|Decimal|float): value to convert
            to (string): coin to convert value to
            prec (int): decimal context precision (decimal number length)
        Returns:
            int|Decimal
        """
        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=prec, rounding=decimal.ROUND_DOWN)
        )

        # PIP in BIP in Decimal
        default = decimal.Decimal(str(cls.DEFAULT))
        # Value in Decimal
        value = decimal.Decimal(str(value))

        # Make conversion
        if to == 'pip':
            value = int(value * default)
        elif to == 'bip':
            value /= default

        # Reset decimal context to default
        decimal.setcontext(context)

        return value 
開發者ID:U-node,項目名稱:minter-sdk,代碼行數:34,代碼來源:__init__.py

示例14: to_bip

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def to_bip(value):
        """
        Convert PIPs to BIPs.
        Use dynamic Decimal precision, depending on value length.
        Args:
            value (int|str|Decimal): value in PIP
        Returns:
            Decimal
        """
        # Check if value is correct PIP value
        value = str(value)
        if not value.isdigit():
            raise ValueError(f'{value} is not correct PIP value')

        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=len(value), rounding=decimal.ROUND_DOWN)
        )

        # Convert value
        value = decimal.Decimal(value) / decimal.Decimal(PIP)

        # Reset decimal context to default
        decimal.setcontext(context)

        return value 
開發者ID:U-node,項目名稱:minter-sdk,代碼行數:30,代碼來源:__init__.py

示例15: test_decimal_independent_of_app

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import getcontext [as 別名]
def test_decimal_independent_of_app():
    d = Decimal('0.1234567890123456789')
    pikepdf_prec = qpdf.get_decimal_precision()
    decimal_prec = getcontext().prec
    try:
        getcontext().prec = 6
        qpdf.set_decimal_precision(8)
        assert str(encode(d)) == '0.12345679'
        assert qpdf.get_decimal_precision() != 6
    finally:
        qpdf.set_decimal_precision(pikepdf_prec)
        getcontext().prec = decimal_prec 
開發者ID:pikepdf,項目名稱:pikepdf,代碼行數:14,代碼來源:test_decimal.py


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