Why does this simple calculation return 0
>>> 25/100*50 0
while this actually calculates correctly?
>>> .25*50 12.5 >>> 10/2*2 10
What is wrong with the first example?
Types of division operators in Python / : Divides the number on its left by the number on its right and returns a floating point value.
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.
In Python 2, the only standard division operator is '/'. If both values are integers, the result is an integer. If either of the values is a float, the return is a float.
In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator '/' returns always a float value. Note: The “//” operator is used to return the closest integer value which is less than or equal to a specified expression or value.
In Python 2, 25/100
is zero when performing an integer divison. since the result is less than 1
.
You can "fix" this by adding from __future__ import division
to your script. This will always perform a float division when using the /
operator and use //
for integer division.
Another option would be making at least one of the operands a float, e.g. 25.0/100
.
In Python 3, 25/100
is always 0.25
.
This is a problem of integer truncation (i.e., any fractional parts of a number are discarded). So:
25 / 100
gives 0
However, as long as at least one of the operands in the division is a float, you'll get a float result:
25 / 100.0
or 25.0 / 100
or 25.0 / 100.0
all give 0.25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With