Python round with `n // 1`

I was wondering if there is a reason not to use an operator //

to round a number to an integer. I haven't seen much on this topic or really know what to look for to find out more.

>>> from random import random
>>> random() * 20 // 1
1.0
>>> random() * 20 // 1
0.0
>>> random() * 20 // 1
16.0
>>> random() * 20 // 1
11.0
>>> random() * 20 // 1
0.0

      

Also, one needs to add 1 to the result (so as not to get a range of 1-20 instead of 0-19) Or is this actual result in the range of 0-20?

+3


source to share


4 answers


The main reason not to use it is that there are already some pretty good built-in functions out there int

and round

that do it already, which are likely to be efficient and won't confuse someone reading your code.

Another reason mentioned in the comments is that it is //1

equivalent math.floor

and not int

or round

. -2.5 // 1

returns a float -3.0

whereas it int(-2.5)

returns an integer -2

.



The fact that experienced programmers can be confused about what it does //1

illustrates well why it is better to use one of the existing functions designed for this purpose - they behave in a way that they are well defined, documented, and consistent.

+3


source


The reason not to use //

to convert a random float to a random int is that you can jump straight to a random int:

>>> import random
>>> random.random()      # [0.0, 1.0)
0.4399641241469895
>>> random.uniform(0,20) # [0.0, 20.0)
11.494311814130072
>>> random.randint(0,20) # [0, 20) or [0, 19]
7

      

To answer your question: x // y

does division by gender by y, so your result will always be rounded. To round to the nearest whole number:



>>> x = 1.7
>>> x // 1
1.0
>>> int(x)
1
>>> (x + 0.5) // 1
2.0
>>> int(x + 0.5)
2
>>> round(x)
2.0
>>> int(round(x))
2

      

Adding 0.5 (or subtracting for a negative number) before converting to an int does the same thing as round(x)

(inline). It is worth noting that it is x // 1

rounded but int(x)

rounded to zero.

Impossible to random.random() * 20 // 1

return 20 because the random is half open. random.uniform(0,20) // 1

however, may return 20, but the probability of this happening is close to zero.

+3


source


Well, //

doesn't round up an integer. Round means to return the nearest integer, but check the following:

print round(1.9)     # 2.0
print 1.9 // 1       # 1.0

      

+1


source


It gives you a range 0-19

, and //

it is actually the division of the sexes, which still gives you a floating point number, but I read what you meant to say.

A possible reason for not using it might be that the // 1

syntax for expressing it is not very concise. Python reads very well and this syntax is not very obvious in what it does. It looks like a JavaScript trick ~~x

.

If I looked through this code, I would suspect a mistake first and the second function.

0


source







All Articles