Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python return 0 for simple division calculation?

Tags:

python

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?

like image 885
fenerlitk Avatar asked May 26 '12 18:05

fenerlitk


People also ask

What does division return in Python?

Types of division operators in Python / : Divides the number on its left by the number on its right and returns a floating point value.

Why does Python division return float?

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?

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.

How does Python implement division?

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.


2 Answers

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.

like image 93
ThiefMaster Avatar answered Sep 29 '22 12:09

ThiefMaster


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

like image 30
Levon Avatar answered Sep 29 '22 12:09

Levon