English 中文(简体)
几轮 to
原标题:Round number to nearest integer

我一直试图四舍五入,如:

32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...

迄今没有成功。 一、导 言 (虽然这将四舍五入或缩小,但这不是我所期望的)和<条形状>(x),后者要么(滚动号码)。

What could I do?

Code:

for i in widthRange:
    for j in heightRange:
        r, g, b = rgb_im.getpixel((i, j))
        h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
        h = h * 360
        int(round(h))
        print(h)
最佳回答

<>strong>TL;DR:

round(x)

它将四舍五入,并改造成愤怒。

您没有将<条码>环绕(h)分配给任何变量。 当您打电话round(h)时,该编码将重新编号,但没有任何其他内容;你必须改变这一行文,以便:

h = round(h)

将新数值分配给<代码>h。


@plowman在评论中说,< <<>>>环绕(>)时,通常会期望做些什么工作,而且,由于该数字作为变量储存的方式,通常无法在屏幕上看到。 >,其中解释了这种行为。

避免这一问题的一个途径是使用

为了在不使用额外图书馆的情况下妥善开展工作,最好使用一种习俗环绕功能。 我提出了以下解决办法,只要我测试避免了所有遗留问题。 该表依据的是代号(repr()(NOTstr(<>!”)。 它看上去不好,但这是我找到解决所有案件的唯一途径。 该公司与Azzal2和Azzal3公司合作。

def proper_round(num, dec=0):
    num = str(num)[:str(num).index( . )+dec+2]
    if num[-1]>= 5 :
        return float(num[:-2-(not dec)]+str(int(num[-2-(not dec)])+1))
    return float(num[:-1])

测试:

>>> print(proper_round(1.0005,3))
1.001
>>> print(proper_round(2.0005,3))
2.001
>>> print(proper_round(3.0005,3))
3.001
>>> print(proper_round(4.0005,3))
4.001
>>> print(proper_round(5.0005,3))
5.001
>>> print(proper_round(1.005,2))
1.01
>>> print(proper_round(2.005,2))
2.01
>>> print(proper_round(3.005,2))
3.01
>>> print(proper_round(4.005,2))
4.01
>>> print(proper_round(5.005,2))
5.01
>>> print(proper_round(1.05,1))
1.1
>>> print(proper_round(2.05,1))
2.1
>>> print(proper_round(3.05,1))
3.1
>>> print(proper_round(4.05,1))
4.1
>>> print(proper_round(5.05,1))
5.1
>>> print(proper_round(1.5))
2.0
>>> print(proper_round(2.5))
3.0
>>> print(proper_round(3.5))
4.0
>>> print(proper_round(4.5))
5.0
>>> print(proper_round(5.5))
6.0
>>> 
>>> print(proper_round(1.000499999999,3))
1.0
>>> print(proper_round(2.000499999999,3))
2.0
>>> print(proper_round(3.000499999999,3))
3.0
>>> print(proper_round(4.000499999999,3))
4.0
>>> print(proper_round(5.000499999999,3))
5.0
>>> print(proper_round(1.00499999999,2))
1.0
>>> print(proper_round(2.00499999999,2))
2.0
>>> print(proper_round(3.00499999999,2))
3.0
>>> print(proper_round(4.00499999999,2))
4.0
>>> print(proper_round(5.00499999999,2))
5.0
>>> print(proper_round(1.0499999999,1))
1.0
>>> print(proper_round(2.0499999999,1))
2.0
>>> print(proper_round(3.0499999999,1))
3.0
>>> print(proper_round(4.0499999999,1))
4.0
>>> print(proper_round(5.0499999999,1))
5.0
>>> print(proper_round(1.499999999))
1.0
>>> print(proper_round(2.499999999))
2.0
>>> print(proper_round(3.499999999))
3.0
>>> print(proper_round(4.499999999))
4.0
>>> print(proper_round(5.499999999))
5.0

最后,更正的答复是:

# Having proper_round defined as previously stated
h = int(proper_round(h))

测试:

>>> proper_round(6.39764125, 2)
6.31 # should be 6.4
>>> proper_round(6.9764125, 1)
6.1  # should be 7

The gotcha here is that the dec/code>-th decimal can be 9 and if the dec+1-th 位数 >=5 the 9 will be a 0 and a 1 shall be carried to the <-1dec/code>-th 位数。

If we take this into consideration, we get:

def proper_round(num, dec=0):
    num = str(num)[:str(num).index( . )+dec+2]
    if num[-1]>= 5 :
      a = num[:-2-(not dec)]       # integer part
      b = int(num[-2-(not dec)])+1 # decimal part
      return float(a)+b**(-dec+1) if a and b == 10 else float(a+str(b))
    return float(num[:-1])

在上述情形中,<代码>b = 10, 而前一个版本将仅设计ab,这将导致对<代码>10<的分类,而线索0将消失。 该版本将<条码>b改为右侧<条码>。

问题回答

Use round(x, y). It will round up your number up to your desired decimal place.

For example:

>>> round(32.268907563, 3)
32.269

<代码>(价值、重大Digit)是普通解决办法,但是,在<代码>5上结束的圆面值时,这种办法不会从数学角度看待。 如果“5在你重新四舍五入之后就在位数中,这些数值有时只是按预期(即8.005<<>>>>>。 数位数为2位数,<>代码>8.01。 对于由于浮动点数点数而导致的某些数值,则四舍五入!

i.e.

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01

Weird。

假设你的意图是进行传统的科学统计工作,这是获得<条码>(<>四>>/代码>功能的手表,按预期需要使用<条码>。 页: 1

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*5),2)

0.08

Aha! 因此,根据这一点,我们能够发挥作用......

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1), digits)

基本上,这增加了一种保证价值,即小于你试图使用<条码>的座标/代码>的最小数字。 加上少量数据,它保存了<代码> 环形<>>> 代码/代码>在多数情况下的行为,而现在则确保数字低于被四舍五入到代码<5>的数值,如果该数值为<代码>4<>>>。

采用<代码>10**(-len(val)-1)的做法是故意的,因为即使删除了“decimal,你所能增加的最小数字也确保了你永远不会改变该轮值。 我可以只使用10**(-len(val),附有一个简略的<代码>if(val>1),以替代1,但更简单地说,总是将<1><>>>>>>>>>>>>>>>细分为“,因为“t”能够大大改变可适用的标准编号范围。 如果贵方的价值观达到这种界限,这种做法将失败,但对于它应当发挥的几乎所有有效价值来说,这种做法将失败。

您也可使用图书馆来完成这项工作,但我提议的内容更为简单,在某些情况下可能更可取。


<><>Edit>: Blckknght 指出<代码>5 fringe case is only for certain Value. 另外,这一答复的较早版本还明确无误地表明,单相干的行为只有在位数与您重新四舍五入的位数位数相差时才会发生。

For positives, try

int(x + 0.5)

To make it work for negatives too, try

int(x + (0.5 if x > 0 else -0.5))

<>代码>int()与地板功能类似,因此,你可以利用这种财产。 这无疑是最快的。

Your solution is calling round without specifying the second argument (number of decimal places)

>>> round(0.44)
0
>>> round(0.64)
1

其结果要好得多

>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0

https://docs.python.org/3/library/Functions.html#round"rel=“noreferer”>https://docs.python.org/3/library/Functions.html#round

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

https://en.wikipedia.org/wiki/Rounding#Round_half_to_even” rel=“noretinger”>,接近一半甚至,详情如下:IEEE 754 ?

仔细重新定义,或使用“非标准”四舍五入......

(另见)

如果你使用 p3。

import numpy as np
x = 2.3
print(np.rint(x))
>>> 2.0

If you need (for example) a two digit approximation for A, then int(A*100+0.5)/100.0 will do what you are looking for.

如果你需要三位数的近似数乘数,并按千分之数。

这样做也是有益的。

import numpy as np    

def proper_round(a):
       
    given any real number  a  returns an integer closest to  a 
       
    a_ceil = np.ceil(a)
    a_floor = np.floor(a)
    if np.abs(a_ceil - a) < np.abs(a_floor - a):
        return int(a_ceil)
    else:
        return int(a_floor)

将x500......四舍五入到x位数的平均值,其依据是正确的方法,与数值的双位调整无关。 采用适当的算法。 高级科学班和统计班教授这一点。 但为什么如此?

尽量减少累积错误!

值四舍五入时,你对该术语采用了错误值。 如果你把各种价值观聚集在一起,你总是把价值提升到[即×+1]的×500......,那么你就会对你的错误积累产生固有的偏见。

在一组N号中,其中M号为x500......,一个圆形方法将引入一个加维差级,即M级,即你四舍五入的0.5位数。

然而,如果你总是四舍五入,那么你就会有expectation<>em>,其中一半的错误术语为+ve,一半为-ve。 因此,你有expecatation,即他们将取消你与M等词的净零差。 error error error error whole whole

但是,这种净误差只是expectation。 当你考虑放弃“fair”硬币(一个类似的问题),即“heads” = +1和“tails”=-1, M倍,并加上所有单壳的总和时,就会出现一种结果的统计期望,但“wander”从0(可以是+ve 还是-ve)到来的程度一般都受到rt(M)的约束,或者它是否标志? 在相当一段时间里,打着打碎了一本统计书。 实际答案(rt或 log)与这一问题无关,因为rt和 log(M)都小于M;1 。

因此,由于涉及我们的数字假设情景,即X500......的M值,因为M是无限的,我们有expectation,即这些M值的错误术语为零,但我们还有一个更强大的expectation,即这一错误术语的规模应当受你四舍五入的0.5位数的约束。

页: 1 页: 1

是的,你可以有病理,你最终将M *0.5归为后,但这种假想应当是一种外观而不是常规,而这种少见的外消作用不会比“双向走”办法更糟。

In the correct answer mentioned in this does not work if I use 79.5. It gives an answer of 710, not 80.

def proper_round(num, dec=0):
num= int(num*pow(10,dec+1))
lastDigit = (str(num))[-1]
num = int(num/10)
if lastDigit >= 5 :
    num+=1
return float(num/pow(10,dec))

上文提及的法典取得了更好的成果。

我使用并可能提出以下解决办法(第3页):

y = int(x + (x % (1 if x >= 0 else -1)))

它对半年数(正数和负数)进行罚款,并比(四)点更快地工作:

round_methods = [lambda x: int(round(x)), 
                 lambda x: int(x + (x % (1 if x >= 0 else -1))),
                 lambda x: np.rint(x).astype(int),
                 lambda x: int(proper_round(x))]

for rm in round_methods:
    %timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

for rm in round_methods:
    print(rm(112.4), rm(112.5), rm(112.6))
    print(rm(-12.4), rm(-12.5), rm(-12.6))
    print( =  * 11)

Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========

This one is tricky, to be honest. There are many simple ways to do this nevertheless. Using math.ceil(), round(), and math.floor(), you can get a integer by using for example:

n = int(round(n))

如果我们在使用这一功能之前,<代码>n = 5.23,我们就会收到<代码>5。 如果你想要四舍五入到不同地点,你就可以利用这一功能:

def Round(n,k):
  point =  %0.  + str(k) +  f 
  if k == 0:
    return int(point % n)
  else:
    return float(point % n)

If we used n (5.23) again, round it to the nearest tenth, and print the answer to the console, our code would be:

Round(5.23,1)

哪些将返回<代码>5.2。 最后,如果你想要把东西四舍五入到最接近的1.2条,你可以使用:

def Round(n,k):
    return k * round(n/k)

If we wanted n to be rounded to 1.2, our code would be:

print(Round(n,1.2))

我们的结果:

4.8

谢谢! 如果有任何问题,请补充评论: (Happy Days!)

用于四舍五入到最接近点数的圆点,使用 n:

p=np.array([     430.15,      57.868,      70.697,      198.13])
p=np.round(p)

页: 1

array([        430,          58,          71,         198])

为此,我只建议:

int(round(x))

这将给你带来最接近的愤怒。

希望!

说明链接。 我在后边谈的那篇文章涉及该守则以及如何使用该守则。

https://kodification.net/python/math/truncate-decimals/

import math

def truncate(number, decimals=0):
    """
    Returns a value truncated to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer.")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more.")
    elif decimals == 0:
        return math.trunc(number)

    factor = 10.0 ** decimals
    return math.trunc(number * factor) / factor




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...