def _index_preshot(self):
logger.info('Index preshot')
# BEGIN DB update
conn = engine.connect()
data_sess = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=conn)
)
for acct in data_sess.query(Account).all():
end_bal = acct.balance.ledger
pctrange = float(end_bal) * 0.1
for i in range(1, 30):
dt = dtnow() - timedelta(days=i)
b = end_bal + Decimal(uniform(-1 * pctrange, pctrange))
b = Decimal(b.quantize(Decimal('.001'), rounding=ROUND_HALF_UP))
acct.set_balance(ledger=b, ledger_date=dt, overall_date=dt)
data_sess.flush()
data_sess.commit()
data_sess.close()
conn.close()
# END DB update
self.get('/')
sleep(1)
python类ROUND_HALF_UP的实例源码
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
def __init__(self, min_value=None, max_value=None, force_string=False,
precision=2, rounding=decimal.ROUND_HALF_UP, **kwargs):
"""
:param min_value: Validation rule for the minimum acceptable value.
:param max_value: Validation rule for the maximum acceptable value.
:param force_string: Store as a string.
:param precision: Number of decimal places to store.
:param rounding: The rounding rule from the python decimal library:
- decimal.ROUND_CEILING (towards Infinity)
- decimal.ROUND_DOWN (towards zero)
- decimal.ROUND_FLOOR (towards -Infinity)
- decimal.ROUND_HALF_DOWN (to nearest with ties going towards zero)
- decimal.ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)
- decimal.ROUND_HALF_UP (to nearest with ties going away from zero)
- decimal.ROUND_UP (away from zero)
- decimal.ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
Defaults to: ``decimal.ROUND_HALF_UP``
"""
self.min_value = min_value
self.max_value = max_value
self.force_string = force_string
self.precision = precision
self.rounding = rounding
super(DecimalField, self).__init__(**kwargs)
def _display_progress_bar(self, size_read):
self._totalread += size_read
if self._show_progress:
if self._totalsize:
percent = float(self._totalread) / float(self._totalsize)
# Output something like this: [==========> ] 49%
sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
'=' * int(decimal.Decimal(percent * 29).quantize(
decimal.Decimal('1'),
rounding=decimal.ROUND_HALF_UP)) + '>', percent
))
else:
sys.stdout.write(
'\r[%s] %d bytes' % (SPIN_CHARS[self._spin_index],
self._totalread))
self._spin_index += 1
if self._spin_index == len(SPIN_CHARS):
self._spin_index = 0
sys.stdout.flush()
def remaining_emission(N_tot, block_n):
# TODO: This is more related to the way QRL works.. Move to another place
"""
calculate remaining emission at block_n: N=total initial coin supply, coeff = decay constant
need to use decimal as floating point not precise enough on different platforms..
:param N_tot:
:param block_n:
:return:
>>> remaining_emission(1, 1)
Decimal('0.99999996')
"""
# TODO: Verify these values and formula
coeff = calc_coeff(config.dev.max_coin_supply, 420480000)
# FIXME: Magic number? Unify
return decimal.Decimal(N_tot * decimal.Decimal(-coeff * block_n).exp()) \
.quantize(decimal.Decimal('1.00000000'), rounding=decimal.ROUND_HALF_UP)
def round2(number, ndigits=None):
"""
Implementation of Python 2 built-in round() function.
Rounds a number to a given precision in decimal digits (default
0 digits). The result is a floating point number. Values are rounded
to the closest multiple of 10 to the power minus ndigits; if two
multiples are equally close, rounding is done away from 0.
ndigits may be negative.
See Python 2 documentation:
https://docs.python.org/2/library/functions.html?highlight=round#round
"""
if ndigits is None:
ndigits = 0
if ndigits < 0:
exponent = 10 ** (-ndigits)
quotient, remainder = divmod(number, exponent)
if remainder >= exponent//2 and number >= 0:
quotient += 1
return float(quotient * exponent)
else:
exponent = _decimal.Decimal('10') ** (-ndigits)
d = _decimal.Decimal.from_float(number).quantize(
exponent, rounding=_decimal.ROUND_HALF_UP)
return float(d)
def __init__(self, min_value=None, max_value=None, precision=2, rounding=decimal.ROUND_HALF_UP, *args, **kw):
super(DecimalField, self).__init__(*args, **kw)
self.min_value = min_value
if self.min_value is not None:
self.min_value = decimal.Decimal(min_value)
self.max_value = max_value
if self.max_value is not None:
self.max_value = decimal.Decimal(max_value)
self.precision = decimal.Decimal(".%s" % ("0" * precision))
self.rounding = rounding
def round_int(dec):
"""Round float to nearest int using expected rounding."""
return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))
def fmt_float(f, p=0):
"""Set float precision and trim precision zeros."""
string = str(
decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP)
)
m = re_float_trim.match(string)
if m:
string = m.group('keep')
if m.group('keep2'):
string += m.group('keep2')
return string
def round_decimal(d: decimal.Decimal) -> decimal.Decimal:
return decimal.Decimal(d).quantize(DECIMAL_QUANTIZE, decimal.ROUND_HALF_UP)
def _getBpm(self):
from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
bpm = None
if frames.BPM_FID in self.frame_set:
bpm_str = self.frame_set[frames.BPM_FID][0].text or u"0"
try:
# Round floats since the spec says this is an integer. Python3
# changed how 'round' works, hence the using of decimal
bpm = int(Decimal(bpm_str).quantize(1, ROUND_HALF_UP))
except (InvalidOperation, ValueError) as ex:
log.warning(ex)
return bpm
def __init__(self,
to_nearest = 1,
rounding = ROUND_HALF_UP,
result_type = DecimalType,
):
# type: (Union[int, Text, DecimalType], Text, type) -> None
"""
:param to_nearest:
The value that the filter should round to.
E.g., ``Round(1)`` rounds to the nearest whole number.
If you want to round to a float value, it is recommended
that you provide it as a string or Decimal, to avoid
floating point problems.
:param rounding:
Controls how to round values.
:param result_type:
The type of result to return.
"""
super(Round, self).__init__()
self.to_nearest = DecimalType(to_nearest)
# Rounding to negative values isn't supported.
# I'm not even sure if that concept is valid.
Min(DecimalType('0')).apply(self.to_nearest)
self.result_type = result_type
self.rounding = rounding
def round_half_up(number):
return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
def round_int(dec):
"""Round float to nearest int using expected rounding."""
return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))
def fmt_float(f, p=0):
"""Set float precision and trim precision zeros."""
string = str(
decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP)
)
m = re_float_trim.match(string)
if m:
string = m.group('keep')
if m.group('keep2'):
string += m.group('keep2')
return string
def round_decimal(x):
return Decimal(x).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
def quantize_tstamp(ts):
return ts.quantize(decimal.Decimal('0.000001'),rounding=decimal.ROUND_HALF_UP)
def test_balance_calcul(self):
"""
Test balance is sum of payments minus sum of purchases
"""
setup()
amount = Decimal(200)
Payment.objects.create(
customer=Customer.objects.get(nickname="jim"),
amount=amount
)
for i in range(25):
if(random.choice((True, False))):
Purchase.objects.create(
customer=Customer.objects.get(nickname="jim"),
product=Product.objects.get(name="Umbrella")
)
amount -= 5
else:
m = random.randrange(0, 20000) / 100
Payment.objects.create(
customer=Customer.objects.get(nickname="jim"),
amount=m
)
amount += Decimal(m)
self.assertEqual(
Customer.objects.get(nickname="jim").balance,
amount.quantize(Decimal('.001'), rounding=ROUND_HALF_UP)
)
def round_half_up(number):
return int(decimal.Decimal(number).quantize(decimal.Decimal('1'),
rounding=decimal.ROUND_HALF_UP
))
def round_half_up(number):
return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
def round_half_up(number):
return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
def to_native(self, value, context=None):
try:
value = Decimal(value).quantize(self.precision, rounding=ROUND_HALF_UP).normalize()
except (TypeError, InvalidOperation):
raise ConversionError(self.messages['number_coerce'].format(value))
if self.min_value is not None and value < self.min_value:
raise ConversionError(self.messages['number_min'].format(value))
if self.max_value is not None and self.max_value < value:
raise ConversionError(self.messages['number_max'].format(value))
return value
advanced_box_score_deserializer_utils.py 文件源码
项目:nba_data
作者: jaebradley
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def parse_float(float_value):
if float_value is None:
return AdvancedBoxScoreDeserializerUtils.default_decimal_value
if not isinstance(float_value, float):
raise ValueError("Expected a float instead of %s", float_value)
return Decimal(Decimal(float_value).quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
advanced_box_score_deserializer_utils.py 文件源码
项目:nba_data
作者: jaebradley
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def parse_percentage(percentage):
if percentage is None:
return AdvancedBoxScoreDeserializerUtils.default_decimal_value
if not isinstance(percentage, float):
raise ValueError("Expected a float instead of %s", percentage)
return Decimal((100 * Decimal(percentage)).quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
def sane_round_int(x):
return int(decimal.Decimal(x).quantize(1, rounding=decimal.ROUND_HALF_UP))
def _add_transactions(self, data_sess, pp):
budgets = list(data_sess.query(Budget).filter(
Budget.is_active.__eq__(True),
Budget.is_income.__eq__(False),
Budget.is_periodic.__eq__(True)
).all())
target = 1950
total = 0
count = 0
while total < target:
count += 1
amt = uniform(0, target * 0.2)
if total + amt > target:
amt = target - total
total += amt
amt = Decimal(Decimal(amt).quantize(
Decimal('.001'), rounding=ROUND_HALF_UP
))
data_sess.add(Transaction(
account_id=1,
budgeted_amount=amt,
actual_amount=amt,
budget=choice(budgets),
date=pp.start_date + timedelta(days=randrange(0, 12)),
description='Transaction %d' % count
))
data_sess.flush()
data_sess.commit()
_compat.py 文件源码
项目:Infrax-as-Code-1000-webservers-in-40-minutes
作者: ezeeetm
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def round_py2_compat(what):
"""
Python 2 and Python 3 use different rounding strategies in round(). This
function ensures that results are python2/3 compatible and backward
compatible with previous py2 releases
:param what: float
:return: rounded long
"""
d = Context(
prec=len(str(long(what))), # round to integer with max precision
rounding=decimal.ROUND_HALF_UP
).create_decimal(str(what)) # str(): python 2.6 compat
return long(d)
def func_round(a, places=0):
""" functor for rounding using standard rules """
return Decimal(a).quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP)
def process(self, resources):
c = local_session(self.manager.session_factory).client('rds')
for r in resources:
old_val = D(r['AllocatedStorage'])
_100 = D(100)
new_val = ((_100 + D(self.data['percent'])) / _100) * old_val
rounded = int(new_val.quantize(D('0'), ROUND_HALF_UP))
c.modify_db_instance(
DBInstanceIdentifier=r['DBInstanceIdentifier'],
AllocatedStorage=rounded,
ApplyImmediately=self.data.get('immediate', False))
def round_int(dec):
"""Round float to nearest int using expected rounding."""
return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP))