Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does integer division return float?

Tags:

python

From what I understand, the integer division // operator is guaranteed to return an integer. However, while 2 // 1 == 1, I also get 2.0 // 1 == 2.0. Why doesn't python produce an integer, and, is it always safe to cast the output to int?

like image 231
blue_note Avatar asked Jun 21 '17 16:06

blue_note


People also ask

Does division return a float?

Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result.

Why does division return a float in Python?

Behavior of the division operator in Python 2.7 and Python 3 // is not "used for integer output". // is the result of the floor() function to the result of the division, which in turns yields an integer if the two operands are integers and a float if at least one of them is a float, for types coherence.

Does Python division always return float?

The result of regular division is always a float, whereas if one of the operands is a float in floor division, then the output will be a float. print(2 / 2, "\tis a float.") print(15 // 4, "\tis an int.")

What happens when you divide an integer by a float?

If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.


1 Answers

You misunderstood the operator. It is a floor division operator, not an integer division operator.

For floating point inputs, it'll still return a floored float value.

From the Binary arithmetic operations section:

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result.

The result of flooring is safe to convert to an integer.

Note that Python applies these rules to almost all numeric types when used in binary arithmetic operations, division and floor division are not exceptional here, nor is this specific to integers and floats (try it with import fractions then 2 // fractions.Fraction(1, 1) for example). The only exception here are complex numbers, for which floor division, modulo operator or divmod() are not defined.

like image 166
Martijn Pieters Avatar answered Oct 25 '22 18:10

Martijn Pieters