问题:在Python中舍入到5(或其他数字)
是否有一个内置函数可以像下面这样四舍五入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
Is there a built-in function that can round like the following?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
回答 0
我不知道Python中的标准函数,但这对我有用:
Python 2
def myround(x, base=5):
return int(base * round(float(x)/base))
Python3
def myround(x, base=5):
return base * round(x/base)
很容易看出上述原因。您要确保将数字除以5是一个正确四舍五入的整数。所以,我们首先做到这些(round(float(x)/5)
这里float
只需要在Python2),然后因为我们除以5,我们乘以5为好。最终转换为int
是因为round()
在Python 2中返回了浮点值。
我通过给它一个base
参数(默认值为5)使该函数更通用。
I don’t know of a standard function in Python, but this works for me:
Python 2
def myround(x, base=5):
return int(base * round(float(x)/base))
Python3
def myround(x, base=5):
return base * round(x/base)
It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(float(x)/5)
where float
is only needed in Python2), and then since we divided by 5, we multiply by 5 as well. The final conversion to int
is because round()
returns a floating-point value in Python 2.
I made the function more generic by giving it a base
parameter, defaulting to 5.
回答 1
对于四舍五入为非整数值,例如0.05:
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
我发现这很有用,因为我可以进行搜索并替换代码,将“ round(”更改为“ myround(”),而不必更改参数值。
For rounding to non-integer values, such as 0.05:
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
I found this useful since I could just do a search and replace in my code to change “round(” to “myround(“, without having to change the parameter values.
回答 2
这只是扩展问题
>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
It’s just a matter of scaling
>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
回答 3
删除“其余”将起作用:
rounded = int(val) - int(val) % 5
如果值是aready,则为整数:
rounded = val - val % 5
作为功能:
def roundint(value, base=5):
return int(value) - int(value) % int(base)
Removing the ‘rest’ would work:
rounded = int(val) - int(val) % 5
If the value is aready an integer:
rounded = val - val % 5
As a function:
def roundint(value, base=5):
return int(value) - int(value) % int(base)
回答 4
def round_to_next5(n):
return n + (5 - n) % 5
def round_to_next5(n):
return n + (5 - n) % 5
回答 5
round(x [,n]):将值四舍五入为乘幂n的最接近10的倍数。所以如果n为负…
def round5(x):
return int(round(x*2, -1)) / 2
由于10 = 5 * 2,您可以对2使用整数除法和乘法,而不是对5.0使用浮点除法和乘法。没关系,除非您喜欢移位
def round5(x):
return int(round(x << 1, -1)) >> 1
round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative…
def round5(x):
return int(round(x*2, -1)) / 2
Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting
def round5(x):
return int(round(x << 1, -1)) >> 1
回答 6
抱歉,我想评论Alok Singhai的回答,但由于缺乏声誉而不能让我= /
无论如何,我们可以概括出另外一个步骤:
def myround(x, base=5):
return base * round(float(x) / base)
这使我们可以使用非整数基,例如.25
或任何其他小数基。
Sorry, I wanted to comment on Alok Singhai’s answer, but it won’t let me due to a lack of reputation =/
Anyway, we can generalize one more step and go:
def myround(x, base=5):
return base * round(float(x) / base)
This allows us to use non-integer bases, like .25
or any other fractional base.
回答 7
divround的修改版本:-)
def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
Modified version of divround :-)
def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
回答 8
用:
>>> def round_to_nearest(n, m):
r = n % m
return n + m - r if r + r >= m else n - r
它不使用乘法,也不会从浮点数转换为浮点数。
四舍五入到最接近的10的倍数:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 10)))
-21 => -20
-18 => -20
-15 => -10
-12 => -10
-9 => -10
-6 => -10
-3 => 0
0 => 0
3 => 0
6 => 10
9 => 10
12 => 10
15 => 20
18 => 20
21 => 20
24 => 20
27 => 30
如您所见,它适用于负数和正数。领带(例如-15和15)将始终向上舍入。
将四舍五入到最接近的5的倍数的类似示例,表明它的行为也与其他“底数”相同:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 5)))
-21 => -20
-18 => -20
-15 => -15
-12 => -10
-9 => -10
-6 => -5
-3 => -5
0 => 0
3 => 5
6 => 5
9 => 10
12 => 10
15 => 15
18 => 20
21 => 20
24 => 25
27 => 25
Use:
>>> def round_to_nearest(n, m):
r = n % m
return n + m - r if r + r >= m else n - r
It does not use multiplication and will not convert from/to floats.
Rounding to the nearest multiple of 10:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 10)))
-21 => -20
-18 => -20
-15 => -10
-12 => -10
-9 => -10
-6 => -10
-3 => 0
0 => 0
3 => 0
6 => 10
9 => 10
12 => 10
15 => 20
18 => 20
21 => 20
24 => 20
27 => 30
As you can see, it works for both negative and positive numbers. Ties (e.g. -15 and 15) will always be rounded upwards.
A similar example that rounds to the nearest multiple of 5, demonstrating that it also behaves as expected for a different “base”:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 5)))
-21 => -20
-18 => -20
-15 => -15
-12 => -10
-9 => -10
-6 => -5
-3 => -5
0 => 0
3 => 5
6 => 5
9 => 10
12 => 10
15 => 15
18 => 20
21 => 20
24 => 25
27 => 25
回答 9
如果有人需要“财务四舍五入”(总是向上0.5舍入):
def myround(x, base=5):
roundcontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(roundcontext)
return int(base *float(decimal.Decimal(x/base).quantize(decimal.Decimal('0'))))
根据文档,其他舍入选项是:
ROUND_CEILING(朝着无穷大),
ROUND_DOWN(朝着零大),ROUND_FLOOR(朝着-无限大),
ROUND_HALF_DOWN(朝着
带零的关系最接近),
ROUND_HALF_EVEN(朝着带偶数的最接近偶数),
ROUND_HALF_UP(远离零)或
ROUND_UP(远离零)。
ROUND_05UP(如果四舍五入后的最后一位数字为零,则为零;否则为零)
默认情况下,Python使用ROUND_HALF_EVEN,因为它具有一些统计上的优势(四舍五入的结果没有偏差)。
In case someone needs “financial rounding” (0.5 rounds always up):
def myround(x, base=5):
roundcontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(roundcontext)
return int(base *float(decimal.Decimal(x/base).quantize(decimal.Decimal('0'))))
As per documentation other rounding options are:
ROUND_CEILING (towards Infinity),
ROUND_DOWN (towards zero),
ROUND_FLOOR (towards -Infinity),
ROUND_HALF_DOWN (to nearest with ties going towards zero),
ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
ROUND_HALF_UP (to nearest with ties going away from zero), or
ROUND_UP (away from zero).
ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
By default Python uses ROUND_HALF_EVEN as it has some statistical advantages (the rounded results are not biased).
回答 10
对于整数和Python 3:
def divround_down(value, step):
return value//step*step
def divround_up(value, step):
return (value+step-1)//step*step
生产:
>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]
For integers and with Python 3:
def divround_down(value, step):
return value//step*step
def divround_up(value, step):
return (value+step-1)//step*step
Producing:
>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]
回答 11
那这个呢:
def divround(value, step):
return divmod(value, step)[0] * step
What about this:
def divround(value, step):
return divmod(value, step)[0] * step
回答 12
下一个5的倍数
考虑到51需要转换为55:
code here
mark = 51;
r = 100 - mark;
a = r%5;
new_mark = mark + a;
Next multiple of 5
Consider 51 needs to be converted to 55:
code here
mark = 51;
r = 100 - mark;
a = r%5;
new_mark = mark + a;
回答 13
这是我的C代码。如果我理解正确,应该应该是这样。
#include <stdio.h>
int main(){
int number;
printf("Enter number: \n");
scanf("%d" , &number);
if(number%5 == 0)
printf("It is multiple of 5\n");
else{
while(number%5 != 0)
number++;
printf("%d\n",number);
}
}
并且四舍五入到最接近的5的倍数,而不仅仅是四舍五入;
#include <stdio.h>
int main(){
int number;
printf("Enter number: \n");
scanf("%d" , &number);
if(number%5 == 0)
printf("It is multiple of 5\n");
else{
while(number%5 != 0)
if (number%5 < 3)
number--;
else
number++;
printf("nearest multiple of 5 is: %d\n",number);
}
}
Here is my C code. If I understand it correctly, it should supposed to be something like this;
#include <stdio.h>
int main(){
int number;
printf("Enter number: \n");
scanf("%d" , &number);
if(number%5 == 0)
printf("It is multiple of 5\n");
else{
while(number%5 != 0)
number++;
printf("%d\n",number);
}
}
and this also rounds to nearest multiple of 5 instead of just rounding up;
#include <stdio.h>
int main(){
int number;
printf("Enter number: \n");
scanf("%d" , &number);
if(number%5 == 0)
printf("It is multiple of 5\n");
else{
while(number%5 != 0)
if (number%5 < 3)
number--;
else
number++;
printf("nearest multiple of 5 is: %d\n",number);
}
}
回答 14
另一种方法(没有显式乘法或除法运算符):
def rnd(x, b=5):
return round(x + min(-(x % b), b - (x % b), key=abs))
Another way to do this (without explicit multiplication or division operators):
def rnd(x, b=5):
return round(x + min(-(x % b), b - (x % b), key=abs))
回答 15
您可以int()
通过添加0.5
到传递的数字来“欺骗” 四舍五入,而不是四舍五入int()
。
You can “trick” int()
into rounding off instead of rounding down by adding 0.5
to the
number you pass to int()
.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。