Divide values in Python - python

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

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

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.

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.

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.

Related

ArcMap Python Field Calculator does not work the same as Python

I am trying to use the python field calculator in ArcMap to do a simple calculation, where:
there are two input variables, the numerator and the denominator
if the numerator is zero a zero is returned
else, the numerator is divided by the denominator and multiplied by 100
The code I tried:
def getScore(num, den):
if num == 0:
return 0
else:
return (num/den) * 100
when I run the script i get no errors yet the 'else' statement is not getting returned.
there will be no zeros in the denominator, so div/0 will not be an issue. The input fields are all 'long' integers and the target field is a 'double.'
I've attached a couple of images showing a test in python where the same exact code works perfectly, as well as the the field calculator where it does not work.
The way ArcGIS Desktop divides integers will result in an integer, so percentages will always end up as zero (e.g. 1 / 10 = 0) -- annoying, and counterintuitive, but that's what it's doing.
ArcGIS Pro uses Python 3 and in ArcGIS Desktop, it uses Python 2. Python 2 uses integer math, meaning that dividing two integer values will always produce an integer value (3 / 2 = 1). In Python 3, dividing two integer values will produce a float (3 / 2 = 1.5).
You can instead explicitly cast the variables as float, which will then do float division and give you a float result (1 / 10 = 0.1). The following works for me:
def getScore(num, den):
if num == 0:
return 0
else:
return (float(num)/float(den)) * 100
One observation: your conditional is basically saying "if the numerator is zero, don't bother dividing, just return zero" -- however, that's what 0 divided by anything is going to be anyway. You can skip the conditional, and the entire codeblock, and just directly calculate -- but still remember to cast the values as float first, or you'll still get a bunch of zeros :)
float(!Healthy!) / float(!Total!)
Isn't this just what you want?
If you do it step by step:
healthy = 1
total = 10
Of course healthy is not 0, so it goes in the else block:
return (healthy / total) * 100
Which is equal to
return (1 / 10) * 100
Which then is equal to:
return (0.1) * 100
Which is 10, just as you get it in the screenshot.

Python 3, context based division

I'm trying to find out if numbers divide cleanly by seeing if they divide into a float or an int, for example:
10/2 = 5
10/3 = 3.333
The problem is, as I understand it, you can either use / and get ONLY float results or use // and get ONLY int results. I'm trying to figure out a way to see if some number n is prime.
The idea I had was to see if all numbers between 1 and n-1 divide into floats, as that would mean none of them divide cleanly.
This is an exercise gauging my ability for an introductory course, I realize there may be some library I can import but I'm supposed to solve this problem using methods that are at my level and importing libraries isn't.
So I was wondering if theres a way to use a divison which will return the true type of the answer, if such a question even makes sense.
To see if a number "divides cleanly", you want to use the %1 operator:
10 % 3 # 1
11 % 3 # 2
12 % 3 # 0
Clearly if a divides b "cleanly", then the result is of b % a is 0.
1Modulus operator

Division error in python, result is incorrectly rounded [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 8 years ago.
I am trying to make a BMI calculator function. I am learning python at pyschools.
This is my code:
# Note: Return a string of 1 decimal place.
def BMI(weight, height):
x = weight /(height*height)
g = round(x,1)
return g
And pyschools shows me that these are the right answers:
With 110 = weight and 2 = height I am supposed to get a BMI of 27,5.
But I instead get 27.
Then it does a second check to make sure I wrote the code right and tells me 24,2 is the right answer but my program did return 24,2. But it still marks my answer in red and says "my" 24,2 is wrong and the website's is right.
If someone has a better site or anything to learn python it would also be appreciated since this website seems to be kind of wrong sometimes. And I am looking for free online resources. No books please.
To fix it for all cases, add this line to the top:
from __future__ import division # Make division work like in Python 3.
in Python 2, / means integer division.
With this in mind, in Python 2 if you pass intgers into division, it will give you an integer back. Anything that would have been a float is floored*. Therefore another option to get the desired result is to pass a float in, so instead of:
weight / (height*height)
do:
float(weight) / (height*height) # float in means float out.
*This means that only full times that the divisor goes in are counted. So 1/2 will get 0 because 2 goes fully into 1 0 times.
def BMI(weight, height):
x = float(weight) /(height*height)
g = round(x,1)
return g
see Python division
and Binary arithmetic operations
The issue lies with your division.
Division as we intrinsically know it is floating point division, or division where 1 / 2 evaluates to a fraction, 0.5. In standard programatic division, the 1, 2 are ints() and therefore cant be fractions, or floats() as the type is called in python. The expression, 1 / 2 therefore evaluates as 0, as 2 as a whole integer cant go into one entirely any times.
Ex:
In [1]: 1 / 2
Out[1]: 0
# Explicitly what is going on, since 1 and 2 are ints.
In [2]: int(1) / int(2)
Out[2]: 0
#fixed with floating division
In [3]: float(1) / float(2)
Out[3]: 0.5
# protip: only one of the divisors needs to be a float for python to divide correctly.
In [4]: 1 / float(2)
Out[4]: 0.5
Use x = weight / float((height*height)) to get the results you expect.
# Note: Return a string of 1 decimal place.
def BMI(weight, height):
x = weight / float((height*height))
g = round(x,1)
return g

Division issues? [duplicate]

This question already has answers here:
Using integer division in Python
(2 answers)
Closed 8 years ago.
Basically i made this program to practice python ( i am a complete noob at it), i am quite enjoying python, as my first programming langauge ever learnt or in the process of i feel very accomplished when completeing a program that works ( even if it is hello world). So anyways, i made a small program using techniques i had learnt from books and stuff from the internet and i have an issue, the program works fine, without problems but at the end there is a division where it justr goes wrong, it cannot divide anything unless it makes a whole number (eg. 100/20=5 but if i did 20/100 it would equel 0 and not 0.2), this also effects it if the number is going to be negative it just panics. i tried 15/20 to see if it was rounding but it still said 0.Any help would be fantastic ^_^
here is the code:
a=100
b=50
c=10
z=110
o=5
zoo=z+o+o
print "What is the value of zoo if:"
print "z=110"
print "o=5"
print "zoo=z+o+o"
import time
time.sleep(5)
print zoo,"of course!"
import time
time.sleep(1)
print "Wait..",a+b-(c)*3,"is the same as zoo except we just did it there using other code!"
import time
time.sleep(3)
print "We did it using 100+50-(10)*3 which then adds to zoo or 120!"
import time
time.sleep(3)
print "were gonna try something fun now!"
import time
time.sleep(2)
print "Please pick a number:"
number=int(raw_input())
print "and another:"
another=int(raw_input())
print "the two numbers you chose multiplied together makes",number*another
import time
time.sleep(2)
print "ok now were going to take your two numbers and divide them"
print "Your two numbers divided=",number/another
import time
time.sleep(1)
print "Ok im bored now, im going to go, have a nice day ^_^"
and here is the awnser with a problem:
What is the value of zoo if:
z=110
o=5
zoo=z+o+o
120 of course!
Wait.. 120 is the same as zoo except we just did it there using other code!
We did it using 100+50-(10)*3 which then adds to zoo or 120!
were gonna try something fun now!
Please pick a number:
15
and another:
20
the two numbers you chose multiplied together makes 300
ok now were going to take your two numbers and divide them
Your two numbers divided= 0
Ok im bored now, im going to go, have a nice day ^_^
oh and im on python 2.7.6
Add above this line:
print "Your two numbers divided=",number/another
this code:
number, another = number + .0, another + .0
The reason your code doesn't work is because you're using int's. When you divide with integers, they return an integer or a whole number. You need to convert the numbers to floats by adding .0 to the numbers. This will allow you to get absolute division results.
You can add
from __future__ import division
at the top of your file. Then the default division strategy will be what you expect, i.e. floating point division. Python 2.7 does integer division by default.
The / quotient of two int's, in Python 2.x, is an int.
The / quotient of one int and one float, in Python 2.x, is a float.
The / quotient of two floats, in Python 2.x, is a float.
The / quotient of two int's, in Python 3.x, is a float.
The / quotient of one int and one float, in Python 3.x, is a float.
The / quotient of two floats in Python 3.x, is a float.
The // quotient of two int's, in Python 3.x, is an int.
The // quotient of one int and one float, in Python 3.x, is a whole-number float.
The // quotient of two floats in Python 3.x, is a whole-number float.
In Python 2.x, you can "from __future__ import division" at the top of your module, to get the 3.x behavior.
So since you're using 2.x, you probably should either "from __future__ import division" at the top of your module, or convert one or both of your int's to float with float(int_var) prior to / division.
To add to all answers. In some languages (including python) division operator result depends on value types being used e.g.:
>>> 1 / 2 # integer divided by integer
0
>>> 1.0 / 2 # float divided by integer
0.5
15/20 = 0 when performing an integer division since the result is less than 1. Therefore it truncates to 0.
// is used for dividing integers and / for floats- you are using the wrong operator so you get an incorrect result:
>>> 15 / 20
0
>>> 15 // 20
0.75
You can fix this by adding from from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division- so just do what you are doing and it will return the expected result:
>>> from __future__ import division
>>> 15 / 20
0.75
I would use the above solution, with the import; but there are other ways. Another option would be making at least one of the operands a float, e.g. float(number) / another.
>>> number = 15
>>> another = 20
>>> float(number) / another
0.75
The above works because the result of the division depends on value types being used, in Python.

Division by Zero Errors

I have a problem with this question from my professor. Here is the question:
Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ).
Here is my code:
def typing_speed(num_words,time_interval):
if(num_words >= 0 and time_interval > 0):
factor = float(60 / time_interval)
print factor
return float(num_words/(factor))
I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently.
Any help is appreciated, thankyou.
When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60):
factor = 60.0 / time_interval
Another way would be divide 60 by float(time_interval)
Note this sample interaction:
In [7]: x = 31
In [8]: 60 / x
Out[8]: 1
In [9]: 60.0 / x
Out[9]: 1.935483870967742
Sharth meant to say: from __future__ import python
Example:
>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>>

Categories

Resources