Question: Divide values in Python

Question

Divide values in Python

Answers 4
Added at 2016-12-09 15:12
Tags
Question

I made a xlrd to json parsing script, which doesn't divide variables. It always returns zero... the code which I am using to divide the variables is:

if not row_values[2]:
   key['nr_one'] = 0
else:
   key['nr_one'] = int(row_values[2])
if not row_values[4]:
   key['nr_two'] = 0
else:     
   key['nr_two'] = int(row_values[4])
try:   
    key['perc'] = float(key['nr_two']/key['nr_one']*100)
except ZeroDivisionError:
    key['perc'] = 0

I have printed the following code at the end of the script:

print('one')
print(key['nr_one'])
print('two')
print(key['nr_two']) 
print('perc')
print(key['perc'])

This returns:

one
103386547
two
135680054
perc
0.0

So. I don't understand why the division fails and returns 0? Could someone please help me format a good way to calculate the percentage

Answers
nr: #1 dodano: 2016-12-09 15:12

Integer division is like this :

1/3 #=> 0

The easiest way to understand this result is not as a fraction, but as the answer to the question "How many times do 3 fit in 1?".

So 0 multiplied by 100 is still :

1/3 * 100 #=> 0

You need

100.0*1/3 #=> 33.333333

For your code :

key['perc'] = 100.0*key['nr_two']/key['nr_one'] (without using float(...))

It returns :

76.1987808465937

NOTE: You really need to type 100.0 (a float), not just 100 (an int). You'd get 76 otherwise.

nr: #2 dodano: 2016-12-09 15:12

it should be float(key['nr_two']) /key['nr_one']*100

nr: #3 dodano: 2016-12-09 15:12

key['nr_two'] is integer and so is key['nr_one']. So when they are divided, the result is forced to be an integer in Python 2x versions (in Python 3x this limitation does not exist and your code would run just fine). What you therefore get, is 0, which is later multiplied by 100, so still 0 but float, 0.0.

nr: #4 dodano: 2016-12-09 15:12

To achieve float division in python 2.x you can just add:

from __future__ import division

This way you will not need to convert your numbers each time you divide them.

Source Show
◀ Wstecz