本文整理汇总了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
示例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)
示例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)
示例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)
示例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))
示例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
示例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...
示例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")))
示例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.")
示例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)
示例11: __init__
# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import getcontext [as 别名]
def __init__(self, context=None):
self.context = context or decimal.getcontext()
示例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
示例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
示例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
示例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