我有两个非常大的整数x, y。我如何在纯Python中计算x/y四舍五入到最接近的整数?X//y会给我正确的答案,但是四舍五入。
由于浮点精度的原因,四舍五入(x/y)不会给出正确的答案。
我希望尽可能避免使用任何库。虽然Decimal可以工作,但我使用的是pypy,而Decimal在pypy中非常慢。如果有一个合适的库,在pypy中是快速的,我很乐意使用它。
例子:
x1 = 10**100 - 1
x2 = 10**100 + 1
y = 2 * 10**100
assert divide(x1, y) == 0
assert divide(x2, y) == 1
assert divide(x1, -y) == 0
assert divide(x2, -y) == -1
assert divide(-x1, y) == 0
assert divide(-x2, y) == -1
assert divide(-x1, -y) == 0
assert divide(-x2, -y) == 1
def divide(x, y): return round(x/y)
给出了所有8个测试用例的0
,没有通过x2
测试用例。
检查余数:
def divide(a, b):
if b < 0:
# Things are a bit more convenient with b and remainder non-negative.
a, b = -a, -b
quotient, remainder = divmod(a, b)
if remainder * 2 > b:
quotient += 1
elif remainder * 2 == b:
# Exactly halfway between two options.
# Handle this case however is appropriate for your use case.
# For example, round-half-to-even would be as follows:
if quotient % 2:
quotient += 1
# else no adjustment needed
return quotient
尝试:
def round_to_nearest_int(x, y):
if x % y <= y / 2:
return x // y
else:
return x // y + 1
在这里,%
用于计算number是否小于或大于等于0.5。如果小于0.5,则x // y
,否则x // y + 1
。
的例子:
round_to_nearest_int(10, 7) => 1
round_to_nearest_int(9, 10) => 1 # here if we do 9 // 10 it will give 0