-3

This is driving me mad... Of all the years I've been using python, this is just now starting to present itself. How I managed to dodge it up until now is beyond me.

If you open a python idle and try this equation...

4/32*100

You'll get '0' as an answer. Now try the same equation using floats....

4.0/32.0*100.0   (or just the first number 4.0/32*100)

You now get an actual percentage.

WTF!?

Is this some kind of python error!? Even a calculation can do the equation and spit out a percentage.

So why can't python see a 4 as 4.0. Better question... What is the interpreter actually seeing if it's not seeing a 4(4.0)?

Someone please clear this up so I can feel professional with python again (lol).

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
chitondihk
  • 105
  • 1
  • 10
  • Are you trying to divide 4/32 and then multiply by 100? If so, cant replicate. – pstatix Nov 13 '17 at 00:36
  • 2
    Are you using Python 2? If so, see https://stackoverflow.com/questions/10768724/why-does-python-return-0-for-simple-division-calculation. TL;DR - integer division rounds values less than 1 to 0. – andrew_reece Nov 13 '17 at 00:37
  • Works for me OK, using Python 3.6. – davo36 Nov 13 '17 at 00:45

2 Answers2

2

In Python 2, int type division ignores the decimal values of the division.

For example, 1/2 = 0.5, but in int type division, 1/2 will evaluate to 0 because it ignores the decimal values.

Thus, in your case with 4/32*100, 4/32will first evaluate to 0 and then 0*100 will finally equal 0.

On the other hand, in float type division, it will evaluate answers as we would expect (not in a strictly precise definition though, look here for further information).

Tatsuya Yokota
  • 444
  • 3
  • 15
0

For Python 2.x, dividing two integers or longs uses integer division, also known as "floor division"(applying the floor function after division)

For Python 3.x, "/" does "true division" for all types.

To make python perform true division, cast any of the denominator for numerator to become float.

float(4)/32*100

or

4/float(32)*100

or doing below to make python 2 division behave like python 3 division

from __future__ import division
4/32*100
Skycc
  • 3,496
  • 1
  • 12
  • 18