Python Forum

Full Version: Division questions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to Python and also refreshing my math...
I have two questions:
- Simple division (/) gives floats even if the result can be a round integer. Why is that? And how can I get a round integer instead of a .0 float? i.e. get the result 2/2=1 instead of 2/2=1.0 I'm not talking about integer division here, because when there is a decimal part I would like to see it. I.e. show a decimal part when it is not .0 Obviously this is relevant when dividing variables where the result is not know if will have a decimal part or not.
- In integer division (//) with one negative number, why is the result rounded down? i.e. why 10//-3=-4?
Thank you!
you can cast your results to integer: int(10/2)
Simple division always creates a float. You can check if the float is an integer and convert back if you would like.

quotient = 10 / 5
if quotient.is_integer():
    quotient = int(quotient)
print(quotient)
Floor division always rounds down. It doesn't round toward zero if that's what you're expecting.
The documentation says

Quote: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.

So division ( / ) returns a float because that is what it is supposed to do.

The same goes for your floor division question. The documentation says 10 // -3 == floor(10 / -3).

The documentation for floor says this:

Quote:math.floor(x)
Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__, which should return an Integral value.

10 / -3 = -3.3333.... floor(-3.3333...) = -4
you can use floor division with double slashes '//' which rounds down
search fro floor division here: https://docs.python.org/3/reference/expressions.html
(Feb-13-2023, 11:13 PM)bowlofred Wrote: [ -> ]Simple division always creates a float. You can check if the float is an integer and convert back if you would like.

quotient = 10 / 5
if quotient.is_integer():
    quotient = int(quotient)
print(quotient)
That's a nice way to do it!
I'm still wondering though, why 4/2 couldn't just give an integer? Why a de facto float result was considered the best choice? After all, multiplication gives inetegers when it can... Why not division too?