Python decimal 模块,getcontext() 实例源码

我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用decimal.getcontext()

项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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,
            context=context
        )


# Date & time fields...
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
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)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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)
项目:aiorestframework    作者:Skorpyon    | 项目源码 | 文件源码
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,
            context=context
        )


# Date & time fields...
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
def KDJ_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
        #sma target round2
        precision = 40
        high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
        if np.isnan(close[-1]):
            return np.array([np.nan]),np.array([np.nan]),np.array([np.nan])
        #K_V, D_V, J_V = self.KDJ_CN(high, low, close)
        K_V, D_V, J_V = self.KDJ_COM(high, low, close)
        if len(K_V) > precision:
            K_V = K_V[precision:]
            D_V = D_V[precision:]
            J_V = J_V[precision:]
        else:
            #print "security:%s no len data precison %s" %(str(security), len(K_V))
            pass
        decimal.getcontext().rounding=decimal.ROUND_HALF_UP
        K_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in K_V])
        D_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in D_V])
        J_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in J_V])
        return K_V, D_V, J_V
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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)
项目:apex    作者:Syncleus    | 项目源码 | 文件源码
def decimal2dms(decimal_degrees):
    """ Converts a floating point number of degrees to the equivalent
    number of degrees, minutes, and seconds, which are returned
    as a 3-element tuple of decimals. If 'decimal_degrees' is negative,
    only degrees (1st element of returned tuple) will be negative,
    minutes (2nd element) and seconds (3rd element) will always be positive.

    Example:

        >>> decimal2dms(121.135)
        (Decimal('121'), Decimal('8'), Decimal('6.000'))
        >>> decimal2dms(-121.135)
        (Decimal('-121'), Decimal('8'), Decimal('6.000'))

    """

    degrees = D(int(decimal_degrees))
    decimal_minutes = libdecimal.getcontext().multiply(
        (D(str(decimal_degrees)) - degrees).copy_abs(), D(60))
    minutes = D(int(decimal_minutes))
    seconds = libdecimal.getcontext().multiply(
        (decimal_minutes - minutes), D(60))
    return (degrees, minutes, seconds)
项目:apex    作者:Syncleus    | 项目源码 | 文件源码
def decimal2dm(decimal_degrees):
    """
    Converts a floating point number of degrees to the degress & minutes.

    Returns a 2-element tuple of decimals.

    If 'decimal_degrees' is negative, only degrees (1st element of returned
    tuple) will be negative, minutes (2nd element) will always be positive.

    Example:

        >>> decimal2dm(121.135)
        (Decimal('121'), Decimal('8.100'))
        >>> decimal2dm(-121.135)
        (Decimal('-121'), Decimal('8.100'))

    """
    degrees = D(int(decimal_degrees))

    minutes = libdecimal.getcontext().multiply(
        (D(str(decimal_degrees)) - degrees).copy_abs(), D(60))

    return (degrees, minutes)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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)
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
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)
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
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)
项目:matasano    作者:shainer    | 项目源码 | 文件源码
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,
项目:pymotw3    作者:reingart    | 项目源码 | 文件源码
def run(self):
        c = decimal.getcontext().copy()
        c.prec = self.prec
        decimal.setcontext(c)
        self.q.put((self.prec, a * b))
项目:panko    作者:openstack    | 项目源码 | 文件源码
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")))
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def opacity(self, value):
        try:
            cleaned_opacity = Decimal(value)
        except (TypeError, ValueError):
            raise ValueError('Invalid opacity')

        if cleaned_opacity < 0:
            cleaned_opacity = Decimal()
        elif cleaned_opacity > 1:
            cleaned_opacity = Decimal(1)
        context = getcontext().copy()
        context.prec = 3
        self._opacity = cleaned_opacity.quantize(Decimal('0.01'), context=context)
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def __init__(self, value='0', rounding=ROUND_CEILING):
        # ????????? ??????????????
        self._formatter = get_formatter()

        # ?????????????? ?????
        context = getcontext().copy()
        context.prec = 18
        context.rounding = rounding
        value = Decimal(value)
        self._value = value.quantize(Decimal('.1') ** self._formatter['decimal_places'], context=context)

        # ????? ? ??????? ?????
        self._int, self._frac = str(self._value).rsplit('.', 1)
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def quantize(self, value):
        """
        Quantize the decimal value to the configured precision.
        """
        context = decimal.getcontext().copy()
        context.prec = self.max_digits
        return value.quantize(
            decimal.Decimal('.1') ** self.decimal_places,
            context=context)


# Date & time fields...
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def cpu_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.cpu * float(self.cpu_coef))
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def ram_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.ram * float(self.ram_coef))
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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))
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
def CCI_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
        #sma target round2
        precision = 14
        high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
        if np.isnan(close[-1]):
            return np.array([np.nan])
        CCI = self.CCI_CN(high, low, close)
        if len(CCI) > precision:
            CCI = CCI[-dataCount:]
        else:
            #print "security:%s no len data precison %s" %(str(security), len(CCI))
            pass
        decimal.getcontext().rounding=decimal.ROUND_HALF_UP
        CCI = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in CCI])
        return CCI
项目:gnocchi    作者:gnocchixyz    | 项目源码 | 文件源码
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")))
项目:cscoins    作者:BrandonWade    | 项目源码 | 文件源码
def __init__(self):
        decimal.getcontext().prec = 5
        self.config_file = ConfigurationFile.ConfigurationFile()
        self.port = 8989
        self.listen_address = "localhost"
        self.server_socket = None
        self.wallets = []
        self.authority_wallet = None
        self.clients = []
        self.ca_name = "unnamed"
        self.transactions = []
        self.coins_per_challenge = 0
        self.minutes_per_challenge = 0
        self.ssl_on = True
        self.ssl_cert = ""
        self.available_challenges = []
        self.prefix_length = 4
        self.challenge_thread = None
        self.max_requests_per_minutes = 30
        self.initial_cooldown_length = 60
        self.invalid_submission_allowed = 5 # within 5 minutes
        self.supervisor_key = ''
        self.emit_coins = False

        self.min_transaction_amount = 0
        self.submissions_allowed_ips = []
        self.statistic = ServerStatistic.ServerStatistic()
        self.read_vars_from_config()
        self.database = ServerDatabase.ServerDatabase(self.config_file.get_string("db_user", "cacoins"), self.config_file.get_string("db_password", ""), self.config_file.get_string("db_name", "cacoins"))

        # commands handler
        self.commands_handler = []
        self.fill_commands_handler()

        self.ca_private_key = None
        self.ca_public_key = None
        self.ca_wallet_id = None

        self.wallet_keys = {}
项目:apex    作者:Syncleus    | 项目源码 | 文件源码
def dms2decimal(degrees, minutes, seconds):
    """ Converts degrees, minutes, and seconds to the equivalent
    number of decimal degrees. If parameter 'degrees' is negative,
    then returned decimal-degrees will also be negative.

    NOTE: this method returns a decimal.Decimal

    Example:

        >>> dms2decimal(121, 8, 6)
        Decimal('121.135')
        >>> dms2decimal(-121, 8, 6)
        Decimal('-121.135')

    """
    decimal = D(0)
    degs = D(str(degrees))
    mins = libdecimal.getcontext().divide(D(str(minutes)), D(60))
    secs = libdecimal.getcontext().divide(D(str(seconds)), D(3600))

    if degrees >= D(0):
        decimal = degs + mins + secs
    else:
        decimal = degs - mins - secs

    return libdecimal.getcontext().normalize(decimal)
项目:listen_tquant    作者:listen-zhou    | 项目源码 | 文件源码
def base_round(val, n):
        if val is not None:
            val = Decimal(val, getcontext())
            return val.__round__(n)
        return None
项目:listen_tquant    作者:listen-zhou    | 项目源码 | 文件源码
def base_round_zero(val, n):
        if val is not None:
            val = Decimal(val, getcontext())
        else:
            val = Decimal(0, getcontext())
        return val.__round__(n)
项目:listen_tquant    作者:listen-zhou    | 项目源码 | 文件源码
def base_round(self, val, n):
        if val is not None:
            val = Decimal(val, getcontext())
            return val.__round__(n)
        return None
项目:listen_tquant    作者:listen-zhou    | 项目源码 | 文件源码
def base_round_zero(self, val, n):
        if val is not None:
            val = Decimal(val, getcontext())
        else:
            val = Decimal(0, getcontext())
        return val.__round__(n)
项目:minitds    作者:nakagami    | 项目源码 | 文件源码
def get_rpc_request_bytes(connection, procname, params=[]):
    buf = _int_to_4bytes(22)
    buf += _int_to_4bytes(18)
    buf += _int_to_2bytes(2)
    buf += connection.transaction_id
    buf += _int_to_4bytes(1)        # request count

    buf += _int_to_2bytes(len(procname))
    buf += _str_to_bytes(procname)
    buf += bytes([0x00, 0x00])      # OptionFlags

    for p in params:
        buf += bytes([0, 0])     # name="", StatusFlags
        if p is None:
            buf += bytes([INTNTYPE, 2])
            buf += bytes([0])
        elif isinstance(p, int):
            buf += bytes([INTNTYPE, 4])
            buf += bytes([4]) + p.to_bytes(4, byteorder='little')
        elif isinstance(p, str):
            ln = len(p) * 2
            buf += bytes([NCHARTYPE]) + ln.to_bytes(2, byteorder='little')
            buf += _int_to_2bytes(connection.lcid) + bytes([0, 0, 0])
            buf += ln.to_bytes(2, byteorder='little') + _str_to_bytes(p)
        elif isinstance(p, decimal.Decimal):
            sign, digits, disponent = p.as_tuple()
            if disponent > 0:
                exp = 256 - disponent
            else:
                exp = -disponent
            v = 0
            ln = len(digits)
            for i in range(ln):
                v += digits[i] * (10 ** (ln - i - 1))
            buf += bytes([DECIMALNTYPE, 9])
            buf += bytes([decimal.getcontext().prec, exp])
            buf += bytes([9, bool(not sign)]) + _int_to_8bytes(v)
        else:
            # another type. pack as string parameter
            s = str(p)
            ln = len(s) * 2
            buf += bytes([NCHARTYPE]) + ln.to_bytes(2, byteorder='little')
            buf += _int_to_2bytes(connection.lcid) + bytes([0, 0, 0])
            buf += ln.to_bytes(2, byteorder='little') + _str_to_bytes(s)

    return buf
项目:cscoins    作者:csgames    | 项目源码 | 文件源码
def __init__(self):
        decimal.getcontext().prec = 5
        self.config_file = ConfigurationFile.ConfigurationFile()
        self.port = 8989
        self.listen_address = "localhost"
        self.server_socket = None
        self.wallets = []
        self.authority_wallet = None
        self.clients = []
        self.ca_name = "unnamed"
        self.transactions = []
        self.coins_per_challenge = 0
        self.minutes_per_challenge = 0
        self.ssl_on = True
        self.ssl_cert = ""
        self.available_challenges = []
        self.prefix_length = 4
        self.challenge_thread = None
        self.max_requests_per_minutes = 30
        self.initial_cooldown_length = 60
        self.invalid_submission_allowed = 5  # within 5 minutes
        self.supervisor_key = ''
        self.emit_coins = False

        self.min_transaction_amount = 0
        self.submissions_allowed_ips = []
        self.statistic = ServerStatistic.ServerStatistic()
        self.read_vars_from_config()
        self.database = ServerDatabase.ServerDatabase(
            self.config_file.get_string(
                "db_user", "cacoins"), self.config_file.get_string(
                "db_password", ""), self.config_file.get_string(
                "db_name", "cacoins"))

        # commands handler
        self.commands_handler = []
        self.fill_commands_handler()

        self.ca_private_key = None
        self.ca_public_key = None
        self.ca_wallet_id = None

        self.wallet_keys = {}