简体   繁体   中英

Dividing a Number by a Decimal Using the Integer Division Operator

What does it mean when you have something like n // float(m) with division imported from __future__ ?

Ex:

>>> x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
>>> y = [2.0 // v for v in x]​
>>> print y
[19.0, 9.0, 6.0, 4.0, 4.0, 3.0, 2.0, 2.0, 2.0, 2.0]

2.0 / 0.1 should yield a 20.0, but I got 19 using //

2.0 / 0.2 is normally a 10, but got a 9

2 / 0.4 is 5. Got 4

Ok... So it looks like it subtracts 1 from the usual answer if it could be an integral type. But then you get to the last one...

2.0 // 1.0 gives 2.0. Same as 2.0 / 1.0 ...

In Python // is the integer division operator, truncating the result. So it will always take the lowest closest integer since floating numbers are not exact if you treat them as integers, unless your numbers can be implicitly cast to integers.

Many decimal numbers can't be exactly expressed as floats, because floats are binary and not decimal. If you print those values to many decimal places you can see how far off they are and in which direction:

0.10000000000000000555
0.20000000000000001110
0.29999999999999998890
0.40000000000000002220
0.50000000000000000000
0.59999999999999997780
0.69999999999999995559
0.80000000000000004441
0.90000000000000002220

If the actual number is a little higher than the decimal representation, the division is going to be a smidge low, and flooring will take it down by 1.

See here for a description of the problem: https://docs.python.org/2/tutorial/floatingpoint.html

PS All integers up to 2**53 can be exactly represented as a float, so the 2.0 really is 2.0 and 1.0 really is 1.0.

I presume you've figured out by now that // is a floor division. float1 // float2 is the same as floor(float1 / float2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM