예제 #1
0
    def decimal_nroot(x, n):
        """Handle nth root of Decimals."""
        assert isinstance(x, decimal.Decimal)
        assert isinstance(n, int)
        if x.is_snan():
            # Signalling NANs always raise.
            raise decimal.InvalidOperation('nth-root of snan')
        if x.is_qnan():
            # Quiet NANs only raise if the context is set to raise,
            # otherwise return a NAN.
            ctx = decimal.getcontext()
            if ctx.traps[decimal.InvalidOperation]:
                raise decimal.InvalidOperation('nth-root of nan')
            else:
                # Preserve the input NAN.
                return x
        if x.is_infinite():
            return x
        # FIXME this hasn't had the extensive testing of the float
        # version _iterated_nroot so there's possibly some buggy
        # corner cases buried in here. Can it overflow? Fail to
        # converge or get trapped in a cycle? Converge to a less
        # accurate root?
        np = n - 1

        def iterate(r):
            return (np * r + x / r**np) / n

        r0 = x**(decimal.Decimal(1) / n)
        assert isinstance(r0, decimal.Decimal)
        r1 = iterate(r0)
        while True:
            if r1 == r0:
                return r1
            r0, r1 = r1, iterate(r1)
예제 #2
0
 def test_init_invalid_rate(self, *args, **kwargs):
     """ Test Account.__init__ with invalid rate input. """
     decimal.setcontext(decimal.BasicContext)
     with self.assertRaises(decimal.InvalidOperation):
         account = self.AccountType(self.owner,
                                    *args,
                                    balance=0,
                                    rate="invalid input",
                                    **kwargs)
         # `rate` is not callable if we use non-callable input
         # pylint: disable=comparison-with-callable
         if account.rate == Decimal("NaN"):
             raise decimal.InvalidOperation()
예제 #3
0
 def get_cones_presence(self):
     """
     To calculate the convolution of cone image on filtered lid CCD image.
     """
     if self.image_cone is None:
         raise decimal.InvalidOperation(
             'cone image not determined, call get_cone()'
             ' before get_cones_presence().')
     self.cone_presence = signal.fftconvolve(
         self.image_cones, self.image_cone, mode='same')
     self.cone_presence = signal.fftconvolve(
         self.cone_presence, high_pass_filter_2525, mode='same')
     self.cone_presence[self.cone_presence < 0] = 0
예제 #4
0
    def test_init_invalid_balance(self, *args, **kwargs):
        """ Test Account.__init__ with invalid balance input. """
        # Let's test invalid Decimal conversions next.
        # (BasicContext causes most Decimal-conversion errors to raise
        # exceptions. Invalid input will raise InvalidOperation)
        decimal.setcontext(decimal.BasicContext)

        # Test with values not convertible to Decimal
        with self.assertRaises(decimal.InvalidOperation):
            account = self.AccountType(self.owner,
                                       *args,
                                       balance="invalid input",
                                       **kwargs)
            # In some contexts, Decimal returns NaN instead of raising an error
            if account.balance == Money("NaN"):
                raise decimal.InvalidOperation()
예제 #5
0
파일: utils.py 프로젝트: dnicolodi/beangulp
def parse_amount(string: str) -> decimal.Decimal:
    """Convert an amount with parens and dollar sign to Decimal."""
    if string is None:
        return Decimal(0)
    string = string.strip()
    if not string:
        return Decimal(0)
    match = re.match(r"\((.*)\)", string)
    if match:
        string = match.group(1)
        sign = -1
    else:
        sign = 1
    cstring = string.strip(' $').replace(',', '')
    try:
        return Decimal(cstring) * sign
    except decimal.InvalidOperation as exc:
        raise decimal.InvalidOperation(
            f"Invalid conversion of {cstring!r}") from exc
예제 #6
0
파일: tax.py 프로젝트: seyhak/TaxRevo
 def __init__(self, entity_code, entity_name, transaction_type, transaction_date, value, quantity_of_stocks):
     self.entity_code = entity_code
     self.entity_name = entity_name
     self.transaction_type = transaction_type
     if transaction_type not in self.TRANSACTION_TYPES:
         error = 'Wrong transaction type {}'.format(transaction_type)
         raise TypeError(error)
     self.date = date.fromisoformat(transaction_date)
     multiplier = 1
     if self.entity_code in self.STOCK_SPLIT_DATES:
         split_info = self.STOCK_SPLIT_DATES.get(self.entity_code)
         if self.date <= date.fromisoformat(split_info.get('date')):
             multiplier = split_info.get('multiplier')
     try:
         value = self.get_formated_input_value(value)
         quantity_of_stocks = self.get_formated_input_value(quantity_of_stocks)
         self.value_usd = decimal.Decimal(value)
         self.quantity_of_stocks = decimal.Decimal(quantity_of_stocks) * decimal.Decimal(multiplier)
     except (ValueError, decimal.InvalidOperation()) as error:
         raise error
     self.single_stock_price = abs(self.value_usd / self.quantity_of_stocks) if self.quantity_of_stocks != 0 else 0
     self.value_pln = 0
     self.usd_price_in_given_date = 0