Monday, 22 January 2024

Division (/) vs floored division (//) in Python

The primary distinction between division (/) and floor division (//) in Python is their approach in dealing with the fractional component of the outcome.

Division (/)

It is often referred as true division, returns a float value as result, irrespective of the operand types. This is the case even when the division's result is mathematically an integer.

>>> 5/2
2.5
>>> 
>>> 4/2
2.0

 

Floor division (//)

This operator carries out floor division by eliminating the fractional part and rounding the result down to the closest whole number. It is applicable to both integers and floating-point numbers.

>>> 5//2
2
>>> 
>>> 4//2
2

Floor division can also be accomplished using the math.floor(x) function, which is beneficial for maintaining consistency when handling both integers and floats.

>>> import math
>>> 
>>> math.floor(5/2)
2

Floor division is useful in situations where you are interested only in the integer part of the result.



 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment