57

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?

That1Guy
  • 7,075
  • 4
  • 47
  • 59
fenerlitk
  • 5,414
  • 9
  • 29
  • 39

6 Answers6

96

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • automatically making a division 0? i just spent an hour debugging that – gary69 Apr 25 '20 at 18:39
  • google deep learning vm, the environment is all setup on python 2, locally i have python 3 and this was baffling me – gary69 Apr 25 '20 at 18:41
20

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

Levon
  • 138,105
  • 33
  • 200
  • 191
  • How would one do this in case that the numbers are stored in a variable? For example x / y, where x = 4 and y = 3. Or x = someObject.size. – altabq Feb 05 '16 at 09:58
  • 4
    One way to do it is tp multiply one of the numbers by 1.0. E.g., `1.0 * x / 2` or you could do `float(x) / 2` - there might be other ways, but these come to mind off the top of my head. You can always interactively verify your results before you code them up in a program. Hope that helps. – Levon Feb 05 '16 at 14:09
1

25/100 is an integer calculation which rounds (by truncation) to 0.

Marcin
  • 48,559
  • 18
  • 128
  • 201
1

I solved this problem just by doing this trick.

(25 * 1.0) / 100 * 50

So, (1.0) makes sure that the numerator be float type

Dharman
  • 30,962
  • 25
  • 85
  • 135
Efrain
  • 31
  • 5
1

Python 2 returns zero for integer division if result is less than 1.

Solution is to convert one of the integers to float e.g.

float(25)/100*50
Ndheti
  • 266
  • 3
  • 18
-4
  • In Python 2: 25/100 is an integer division by default

  • In Python 3: 25/100 is always 0.25.

Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
javase
  • 1
  • 1
  • 10