在Python中舍入到5(或其他数字)

发布于 2025-02-10 20:55:32 字数 161 浏览 4 评论 0 原文

是否可以像以下内容一样围绕内置功能?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

泪冰清 2025-02-17 20:55:33

对于舍入到非全能值的舍入,例如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.

神爱温柔 2025-02-17 20:55:33

这只是扩展的问题

>>> 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
为你拒绝所有暧昧 2025-02-17 20:55:33

删除“静止”将有效:

rounded = int(val) - int(val) % 5

如果值是acthy a acte a integer:

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)
尐偏执 2025-02-17 20:55:33
def round_to_next5(n):
    return n + (5 - n) % 5
def round_to_next5(n):
    return n + (5 - n) % 5
千秋岁 2025-02-17 20:55:33
def round_up_to_base(x, base=10):
    return x + (-x % base)

def round_down_to_base(x, base=10):
    return x - (x % base)

给出

base = 5

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

for base = 10

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

在Python> = 3.7.9中测试

def round_up_to_base(x, base=10):
    return x + (-x % base)

def round_down_to_base(x, base=10):
    return x - (x % base)

which gives

for base=5:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

for base=10:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

tested in Python >= 3.7.9

一袭白衣梦中忆 2025-02-17 20:55:33

圆形(x [,n]):值将圆形到最接近10的倍数n。因此,如果n为负...

def round5(x):
    return int(round(x*2, -1)) / 2

由于10 = 5 * 2,则可以使用2个整数除法和乘法,而不是float Disemant和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
捶死心动 2025-02-17 20:55:33

抱歉,我想对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.

极度宠爱 2025-02-17 20:55:33

使用:

>>> 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
凤舞天涯 2025-02-17 20:55:33

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
焚却相思 2025-02-17 20:55:33

另一种做到这一点的方法(没有明确的乘法或划分运算符):

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))
葬心 2025-02-17 20:55:33

如果有人需要“财务圆形”(总是0.5回合):

from decimal import ROUND_HALF_UP, Decimal, localcontext

def myround(x, base: int = 5):
    # starting with Python 3.11:
    # with localcontext(rounding=decimal.ROUND_HALF_UP):
    with localcontext() as ctx:
        ctx.rounding = ROUND_HALF_UP
        return base * int(decimal.Decimal(x / base).quantize(Decimal('0')))

文档圆形选项为:

  • round_ceiling (to infinity
  • round_down (to Zero)
  • round> round_floor (to -Infinity
  • round_half_down (到最接近零的关系)
  • round_half_even (到最接近的纽带,均为最接近整数)
  • round_half_up (到距离零的领带最接近)
  • round_up (远离零)
  • round_05up 是0或5;

默认情况下,python

In case someone needs "financial rounding" (0.5 rounds always up):

from decimal import ROUND_HALF_UP, Decimal, localcontext

def myround(x, base: int = 5):
    # starting with Python 3.11:
    # with localcontext(rounding=decimal.ROUND_HALF_UP):
    with localcontext() as ctx:
        ctx.rounding = ROUND_HALF_UP
        return base * int(decimal.Decimal(x / base).quantize(Decimal('0')))

As per documentation the 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)
  • 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).

动听の歌 2025-02-17 20:55:33

对于整数和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]
陌伤ぢ 2025-02-17 20:55:33

我想没有人真正写过这篇文章,但是您可以做:

round(12, -1) --> 10
round(18, -1) --> 20

No one actually wrote this yet I guess but you can do:

round(12, -1) --> 10
round(18, -1) --> 20
心清如水 2025-02-17 20:55:33

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;
狼性发作 2025-02-17 20:55:33

那呢:

 def divround(value, step):
     return divmod(value, step)[0] * step

What about this:

 def divround(value, step):
     return divmod(value, step)[0] * step
倒带 2025-02-17 20:55:33

我需要将前5个。

示例16回合降至15或19发,降至15,

这是所使用的代码

    def myround(x,segment):
        preRound = x / segment
        roundNum = int(preRound)
        segVal = segment * roundNum
        return segVal

I needed to round down to the preceding 5.

Example 16 rounds down to 15 or 19 rounds down to 15

Here's the code used

    def myround(x,segment):
        preRound = x / segment
        roundNum = int(preRound)
        segVal = segment * roundNum
        return segVal
柏林苍穹下 2025-02-17 20:55:33

这是我的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);
  }
}
怎会甘心 2025-02-17 20:55:33

接受的答案的补充,以指定舍入或下到最接近的5左右

import math

def my_round(x, base, down = True):
    return base * math.floor(x/base) + (not down) * base

An addition to accepted answer, to specify rounding up or down to nearest 5-or-whatever

import math

def my_round(x, base, down = True):
    return base * math.floor(x/base) + (not down) * base
眼波传意 2025-02-17 20:55:33

一种仅适用于 int s的解决方案(它接受 float s,但是圆形的行为就像小数组件不存在),但是与任何依赖临时的解决方案不同转换为 float (所有 Math.floor / Math.ceil 基于基于的解决方案,使用/的所有解决方案,大多数使用 rough )的解决方案,它适用于任意巨大的 int 输入,永不失去精度,永不提高异常或导致无穷大值。

这是最简单的解决方案 down 到一个数字的下一个次数

def round_to_nearest(num, base=5):
    num += base // 2
    return num - (num % base)

它基于的圆形配方仅仅是:

def round_down(num, base=5):
    return num - (num % base)

唯一的更改是,您提前将基础添加到数字中,因此它圆形到最接近。使用确切的中点值,只有使用 base s,因此, round_to_nearest(3,6)才能围绕 6 而不是<代码> 0 ,而 round_to_nearest(-3,6)将得到 0 而不是 -6 。如果您更喜欢中点值,则可以将第一行更改为 num +=(base -1)// 2

A solution that works only with ints (it accepts floats, but the rounding behaves as if the decimal component doesn't exist), but unlike any solution relying on temporary conversion to float (all the math.floor/math.ceil-based solutions, all the solutions using /, most solutions using round), it works for arbitrarily huge int inputs, never losing precision, never raising exceptions or resulting in infinity values.

It's an adaptation of the simplest solution for rounding down to the next lower multiple of a number:

def round_to_nearest(num, base=5):
    num += base // 2
    return num - (num % base)

The round down recipe it's based on is just:

def round_down(num, base=5):
    return num - (num % base)

the only change is that you add half the base to the number ahead of time so it rounds to nearest. With exact midpoint values, only possible with even bases, rounding up, so round_to_nearest(3, 6) will round to 6 rather than 0, while round_to_nearest(-3, 6) will round to 0 rather than -6. If you prefer midpoint values round down, you can change the first line to num += (base - 1) // 2.

喵星人汪星人 2025-02-17 20:55:33
from math import isclose

def myPrice (p1,p2):
    return isclose(p1, p2, rel_tol=0.05)

print(myPrice(50.10,50.20)) 

要设置5%的公差,请通过rel_tol = 0.05。默认公差为1E-09

from math import isclose

def myPrice (p1,p2):
    return isclose(p1, p2, rel_tol=0.05)

print(myPrice(50.10,50.20)) 

To set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09

卷耳 2025-02-17 20:55:33

我发现这比 @mkrieger1和@alok singhal的答案要慢得多,但它更明确地说明了圆形行为,并且更易于修改或扩展。

def round_up_to_5(num):
    rounded_num = math.ceil(num / 5) * 5
    return int(rounded_num)

I find this one to be negligibly slower than the answer by @mkrieger1 and @Alok Singhal but it is more explicit about the rounding behavior and easier to modify or extend.

def round_up_to_5(num):
    rounded_num = math.ceil(num / 5) * 5
    return int(rounded_num)
愿与i 2025-02-17 20:55:33

您可以“技巧” int()进行四舍五入
您传递给 int()的号码。

You can “trick” int() into rounding off instead of rounding down by adding 0.5 to the
number you pass to int().

水波映月 2025-02-17 20:55:32

我不知道Python中的标准功能,但这对我来说有用:

Python 3

def myround(x, base=5):
    return base * round(x/base)

很容易理解上述原因。您要确保您的电话号码除以5是一个整数,正确圆形。因此,我们首先做到这一点(回合(x/5)),然后自从我们除以5,我们也乘以5。

我通过给出 base 参数,默认为5。python

2

在Python 2中, float(x)将需要使用 python 2,从而 使该功能更加通用。 /确实需要浮点线,并且需要最终转换为 int ,因为 round()返回Python 2中的浮点值。

def myround(x, base=5):
    return int(base * round(float(x)/base))

I don't know of a standard function in Python, but this works for me:

Python 3

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(x/5)), and then since we divided by 5, we multiply by 5 as well.

I made the function more generic by giving it a base parameter, defaulting to 5.

Python 2

In Python 2, float(x) would be needed to ensure that / does floating-point division, and a final conversion to int is needed because round() returns a floating-point value in Python 2.

def myround(x, base=5):
    return int(base * round(float(x)/base))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文