本文整理汇总了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
示例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
示例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))
示例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
示例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
示例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
示例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
示例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())
示例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
示例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
示例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
示例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))
示例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
示例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')
示例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