如何在Python中实现round函数

问题描述 投票:0回答:1

发布了很多答案,但无法理解Python中的

round
函数到底是如何工作的。

我们可以采用多种方法对数字进行四舍五入:

 1. Round up
 2. Round down
 3. Round half up
 4. Round half down
 5. Round half away from zero
 6. Round half even (Bankers rounding)

我可以理解并实现除 6 之外的所有舍入技术。圆半均匀技术。

如果出现平局,

Round half even
将进行四舍五入(当舍入数字后恰好有
0.5
时),并将数字四舍五入到最接近的偶数。因此,
round(14.5)
会将其舍入为
14
,因为
14.5
位于
14
15
之间,但
14
是最接近的偶数。但是
round(15.5)
会给出
16
,因为
16
是闭偶数。

但是对于其他情况,例如

round(7.895, 2)
round(7.815, 2)
round(7.855, 2)
round(7.85, 1)
round(7.35, 1)
round(7.25, 1)
),这变得非常难以理解。我现在不明白舍入是如何工作的,它们给出了非常奇怪的值,很难理解。

这里是不同舍入方法的实现,除了我想了解如何实现的

round half to even

1。四舍五入

def round_up(num, place=0):
    power = 10 ** place
    return math.ceil(num * power) / power

2。向下舍入

def round_down(num, place=0):
    power = 10 ** place
    return math.floor(num * power ) / power

3.向上四舍五入

def round_half_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier + 0.5) / multiplier

4。向下圆一半

def round_half_down(n, decimals=0):
    power = 10 ** decimals
    return math.floor(n * power + 0.4) / power

5。从零开始舍入一半

def round_half_away_from_zero(num, decimals=0):
    power = 10 ** decimals
    return math.copysign(math.floor(abs(num) * power + 0.5) / power, num)

6。四舍五入(银行四舍五入)

如何实现圆半偶方法?

python python-3.x algorithm rounding
1个回答
0
投票

该术语被称为

bankers rounding method
,因为银行家需要四舍五入的情况是 - 当他们想要跳过较低的货币单位时。 例如:让我们举一个不同国家的货币单位的例子。

说出他们是否想要四舍五入: 美元和美分四舍五入为仅美元(或) 英镑和便士四舍五入为英镑 欧元和美分四舍五入为仅欧元 迪拉姆和菲尔四舍五入为迪拉姆 卢比和派萨四舍五入为卢比

因此,如果小数部分恰好是 0.50,它将转换为最接近的偶数。即使是0.51,舍入方法也是普通方法

print(round(2.5))
#output: 2. Because 2 is the even number. If rounded off to 3, 3 is odd

print(round(6.50))
#outout 6. Because 7 is an odd number

print(round(7.5))
#output 8. Because 7 is an odd  number

print(round(6.51))
#output : 7. Because 6.51 is more than 6.5

它会四舍五入最接近的偶数 - 仅当小数为 0.5 或 0.50 或 0.500 等时,它也适用于在小数之前找到的数字。并适用于每一位小数。例如,

print(round(7.525, 2))
output: 7.53

在上面的示例中,输出是 7.53 而不是 7.54。因为这里四舍五入是小数位。因此,如果下一个小数大于 5,则使用传统的四舍五入方法。

© www.soinside.com 2019 - 2024. All rights reserved.