Python decimal.getcontext() Examples

The following are 30 code examples of decimal.getcontext(). 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: test_decimal.py    From recruit with Apache License 2.0 8 votes vote down vote up
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 
Example #2
Source File: utils.py    From python2017 with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #4
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #5
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 #6
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: test_decimal.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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 
Example #8
Source File: test_decimal.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: fields.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
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... 
Example #10
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: recipe-578478.py    From code with MIT License 6 votes vote down vote up
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)) 
Example #12
Source File: utils.py    From python with Apache License 2.0 6 votes vote down vote up
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) 
Example #13
Source File: array.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def __init__(self, context=None):
        self.context = context or decimal.getcontext() 
Example #14
Source File: test_python_to_sql.py    From ctds with MIT License 5 votes vote down vote up
def test_decimal(self):
        with self.connect() as connection:
            with connection.cursor() as cursor:
                for value, precision, scale in  (
                        (decimal.Decimal(0), 1, 0),
                        (decimal.Decimal('1.1'), 2, 1),
                        (decimal.Decimal('0.1'), 2, 1),
                        (decimal.Decimal('-1.234567'), 7, 6),
                        (decimal.Decimal('1234567.890123'), 13, 6),
                        (decimal.Decimal('-1234567.890123'), 13, 6),
                        (decimal.Decimal('4.01E+8'), 9, 0),
                        (decimal.Decimal('-1.54E+11'), 12, 0),
                        (decimal.Decimal('0.004354'), 7, 6),
                        (decimal.Decimal('900.0'), 4, 1),
                        (decimal.Decimal('54.234246451650'), 14, 12),
                        (
                            decimal.Decimal('.{0}'.format('1' * decimal.getcontext().prec)),
                            decimal.getcontext().prec + 1,
                            decimal.getcontext().prec
                        ),
                ):
                    row = self.parameter_type(cursor, value)
                    self.assertEqual('decimal', row.Type)

                    self.assertEqual(row.Precision, precision, repr(value))
                    self.assertEqual(row.Scale, scale, repr(value))
                    self.assertEqual(row.Value, value) 
Example #15
Source File: svg_regex.py    From beampy with GNU General Public License v3.0 5 votes vote down vote up
def rule_coordinate(self, next_val_fn, token):
        if token[0] not in self.number_tokens:
            raise SyntaxError("expecting a number; got %r" % (token,))
        x = getcontext().create_decimal(token[1])
        token = next_val_fn()
        return x, token 
Example #16
Source File: svg_regex.py    From beampy with GNU General Public License v3.0 5 votes vote down vote up
def rule_coordinate_pair(self, next_val_fn, token):
        # Inline these since this rule is so common.
        if token[0] not in self.number_tokens:
            raise SyntaxError("expecting a number; got %r" % (token,))
        x = getcontext().create_decimal(token[1])
        token = next_val_fn()
        if token[0] not in self.number_tokens:
            raise SyntaxError("expecting a number; got %r" % (token,))
        y = getcontext().create_decimal(token[1])
        token = next_val_fn()
        return [x, y], token 
Example #17
Source File: exch_api.py    From Crypto_trading_robot with MIT License 5 votes vote down vote up
def bitmex_convert_price(self, market, price):

        tickSize = self.bitmex_ticksize(market)
        getcontext().rounding = 'ROUND_DOWN'
        price = Decimal(str(price))
        price = price.quantize(Decimal(str(tickSize)))

        return price

    # Return the ticksize for a specific market 
Example #18
Source File: ch42.py    From matasano with GNU General Public License v3.0 5 votes vote down vote up
def cube_root(x):
    """Required because the usual x ^ 1/3 does not work with big integers."""
    decimal.getcontext().prec = 2 * len(str(x))
    power = decimal.Decimal(1) / decimal.Decimal(3)
    x = decimal.Decimal(str(x))
    root = x ** power

    integer_root = root.quantize(decimal.Decimal('1.'), rounding=decimal.ROUND_DOWN)
    return int(integer_root)

# Taken from Hal Finney's summary at https://www.ietf.org/mail-archive/web/openpgp/current/msg00999.html, 
Example #19
Source File: storage.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def size_total(self):
        # We are working with decimal objects and rounding everything down
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(int(self.size) * float(self.size_coef)) 
Example #20
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def cpu_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.cpu * float(self.cpu_coef)) 
Example #21
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def ram_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.ram * float(self.ram_coef)) 
Example #22
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def resources(self):
        """Return tuple with total (cpu, ram, disk) resources"""
        # We are working with decimal objects and rounding everything down
        decimal.getcontext().rounding = decimal.ROUND_DOWN

        # The total local disk size should not include backups and snapshots
        # TODO: fix ns.size_images and subtract it too
        disk_size_total = self.storage.size_total
        if self._ns:
            disk_size_total -= self._ns.size_backups + self._ns.size_snapshots + self._ns.size_rep_snapshots

        return self.cpu * float(self.cpu_coef), self.ram * float(self.ram_coef), disk_size_total 
Example #23
Source File: wl_serialization.py    From WolframClientForPython with MIT License 5 votes vote down vote up
def test_numeric(self):

        prec = decimal.getcontext().prec

        self.compare(
            decimal.Decimal(10 ** 20), force_bytes("100000000000000000000``%i" % prec)
        )
        self.compare(decimal.Decimal("100"), force_bytes("100``%i" % prec))
        self.compare(decimal.Decimal("100.00"), force_bytes("100.00``%i" % prec))
        self.compare(decimal.Decimal("0.010"), force_bytes("0.010``%i" % prec))
        self.compare(decimal.Decimal("0.1534"), force_bytes("0.1534``%i" % prec))
        self.compare(decimal.Decimal("0.0000000010"), force_bytes("0.0000000010``%i" % prec))

        self.compare(decimal.Decimal("0"), force_bytes("0``%i" % prec))
        self.compare(decimal.Decimal("0.0"), force_bytes("0.0``%i" % prec))
        self.compare(decimal.Decimal("0.0000000000"), force_bytes("0.0000000000``%i" % prec))

        self.compare(fractions.Fraction(1, 2), wl.Rational(1, 2))

        self.compare(float("0.150000"), b"0.15")

        for special, result in (
            [float("inf"), self.dumps(wl.DirectedInfinity(1))],
            [float("-inf"), self.dumps(wl.DirectedInfinity(-1))],
            [float("nan"), self.dumps(wl.Indeterminate)],
        ):
            self.compare(special, result)
            self.compare(decimal.Decimal(special), result) 
Example #24
Source File: utils.py    From WolframClientForPython with MIT License 5 votes vote down vote up
def py_encode_decimal(number, prec=decimal.getcontext().prec):
    return "{0:f}``{1:d}".format(number, prec).encode("utf-8") 
Example #25
Source File: textual.py    From GeoVis with MIT License 5 votes vote down vote up
def encode(obj, encoding="utf-8", strlen=150, floatlen=16, floatprec=6):
    try:
        #encode as decimal nr
        float(obj)
        decimal.getcontext().prec = floatprec
        obj = str(decimal.Decimal(str(obj))) [:floatlen]
    except:
        #encode as text
        try:
            obj = obj.encode(encoding)
        except:
            obj = obj.encode("latin") #backup encoding to encode as
    return obj 
Example #26
Source File: datatypes.py    From brownie with MIT License 5 votes vote down vote up
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.") 
Example #27
Source File: utils.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #28
Source File: array.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, context=None):
        self.context = context or decimal.getcontext() 
Example #29
Source File: solution_1.py    From ProjectEuler with MIT License 5 votes vote down vote up
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 
Example #30
Source File: __init__.py    From minter-sdk with MIT License 5 votes vote down vote up
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