Python math division operation returns 0 - python

print "------------ EPIDEMIOLOGY --------------\n"
def divide(A,B):
return A/B
print " [Population] point Prevalence rate: "
A = input("Enter value for people with disease: " )
B = input("Enter value for total population: " )
prevalence = divide(A,B)
print " Population Prevalence rate is: ",prevalence
A and B are user input and do not know if they are integers or floats. My answer is always 0 when i run this program. (I'm new in Python). How do i fix this or change in my function to avoid this problem?
the input part of code works, the math does not.

You get the answer 0 because you are using Python2 and performing integer division. The fact that the population with disease cannot be higher than the total population is the reason that you get zero for every reasonable input (except when both values are the same).
Two fixes:
def divide(a,b):
if b == 0:
# decide for yourself what should happen here
else:
return float(a)/b
This will make sure that your function performs floating point division, not matter what numbers you pass to it. The second fix is that you should use raw_input in Python2 and cast the input to a number (float would be fine here).
a = float(raw_input("Enter value for people with disease: ")) # add error checking as needed
b = float(raw_input("Enter value for total population: " )) # add error checking as needed
The problem with input() is that it is equivalent to eval(raw_input()).

In python 2.x is performed integer division. If dividend is less than divisor, the operation returns zero.
So you have two options:
Make one of operands as float:
def divide(A,B):
return float(A)/B
import feature from Python 3
from __future__ import division
print "------------ EPIDEMIOLOGY --------------\n"
def divide(A,B):
return A/B

Related

I don't see my error here - Trying to learn Python

I'm trying to become comfortable with python. I've been trying some simple activities that I've given in my beginning c++ classes when I was teaching. I did one involving functions and writing a file which worked flawlessly. I thought this one would be easier. It acts like it is in a silent endless loop, but it won't even let me trace it. Can someone see where I am going awry?
# Find Adam Numbers
def isAdamNumber(candidate):
isAdam = False
rev = reverse(candidate)
square = candidate * candidate
revsq = rev*rev
if revsq == reverse(square):
isAdam = True
return isAdam
def reverse(num):
rev=0
while num > 0:
rev = rev * 10 + num%10
num/=10
return rev
for x in range (11,25):
if isAdamNumber(x):
print(x, " is an adam number\n")
The quick fix is to change /= with the integer division version, //=
Inside the reverse function, you are going into an infinite loop. num value always will be greater than 0, therefore the while loop will continuously run. In python, you can get the reverse of the function without much effort. Convert the integer to string and reverse the string and now change the string back to integer.
def reverse(num):
num_str = str(num)[::-1]
return int(num_str)
I think this function definition can solve your problem.
To visualize the python to learn and teach, use this link
The problem has already been addressed by the other answers, so here's the expanded and simplified version of the slicing that's going on [this doesn't actually use slicing]:
def reverse(num):
rev = ''
num = str(num)
for i in range(len(num) - 1, -1, -1):
rev += num[i]
return int(rev)
This counts backward from the last element in the string version of num, and adds all the elements of num (in reverse order) to rev.
num > 0 is never False. Dividing a positive number by 10 repeatedly makes it smaller, but it never becomes zero, so the while loop keeps repeating.
Use //= instead. It rounds to the nearest integer, so it will reach 0.
This also wouldn't reverse numbers (unless I'm missing something). Alternatively, you can use
int(str(num)[::-1])
which converts the number to a string, reverses it using slicing, and turns it back into an integer.

Extract decimal part of a floating point number

I have a function that takes a float as an input and the output is only the decimal part.
For example, get_decimal(4.45) should return 0.45, and we should only return positive figures.
I made the following code:
def get_decimal(n):
try:
return float('0.'+(str(n).split('.',1))[1])
except:
return 0
And this code almost works, but it doesn't give the whole answer.
For example get_decimal(4.566666678258757587577) only returns:
0.566666678258757
instead of:
0.566666678258757587577
Is there a way to get the whole number?
Use the modulus:
inp = 4.566666678258757587577
output = inp % 1
print(output) # prints 0.566666678259
Note that Python's print() function usually attempts to display a more human readable form of a floating point number. So, while the printed value appears to stop after 12 digits, there is more precision beyond that not shown.
Consider:
print((output * 100000) % 1) # prints 0.667825875724
# 4.566666678258757587577 <- original input
you can try this :
output = round(inp-int(inp),abs(decimal.Decimal(str(inp)).as_tuple().exponent)
you can use Decimal but in that case you need to set your input as string:
from decimal import *
def get_decimal(n):
try:
return Decimal('0.'+(str(n).split('.',1))[1])
except:
return 0
print(get_decimal("4.5666666782587575875779"))
output:
0.5666666782587575875779

How to define new variable as float?

I'm trying to make the following function output the correct answer, but the 'rightSide' variable is being made as an integer, and doesn't have any decimals.
def G(mass1, mass2, radius, force):
rightSide=(mass1*mass2)/(radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")
I just want all the variables to be floats, but the problem starts with 'rightSide'.
I tried the following with no success:
float(rightSide)=(mass1*mass2)/(radius**2)
--
rightSide=(float(mass1)*float(mass2))/(float(radius)**2)
Any tips? Thanks!
Nevermind, I just re-ran the second code that I hand typed in the question and it worked -_-
In general
x = float(2)
Or
y = 10
x = float(y)
In your case,
rightSide=float((mass1*mass2)/(radius**2))
You need to make one of the inputs a floating point value. Try changing 2 to 2.0. E.g.:
>>> x=10
>>> x**2
100
>>> x**2.0
100.0
Note that in Python 3 division automatically returns a floating point, and the new // operator explicitly does integer division.
Try this:
def G(mass1, mass2, radius, force):
rightSide = (float(mass1)*mass2) / (radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")

How to find value of this series using python?

i m new to python and its great!. but i m facing difficulties in finding the result of this series:
1-x+(x^2)/2!-(x^3)/3!+(x^4)/4!-..............up to n terms
what i wrote was:
import math
a=input("ENter the no")
x=input("ENter value of x")
i=1
s=0
s1=0
s2=1
p=1
while(i<=a):
if(i%2!=0):
s=s-math.pow(x,i)/p*i
else:
s1=s1+math.pow(x,i)/p*i
i=i+1
else:
s2=s2+s1+s
print s2
please let me know of the correct program and the mistakes:)!! Thanks in advance.
let me know it without directly using the factorial function?
This is the Taylor's series development of exp(-x). Recognizing this gives you a good opportunity to check your result against math.exp(-x).
Simple syntax improvements
You don't need an 'else' after the while. Just add the code to be run after the loop at the same indentation level as before the while loop.
Mathematical problems
Most importantly, the computing of the factorial is simply never done. Writing p*i does not store in p the product of p and i. You need to do that.
Then, there is a problem with the operator precedence. When you write pow(...)/p*i, Python understands ( pow(...) / p ) * i, which is not what you mean.
Finally, most of the terms in the series cancel out, but you add all positive terms on one side and all negative terms on the other. This means that you will grow two very big values (and risk overflows if you were using integers), and then take the difference between them to get the result. Because double precision on a computer is finite, this is a bad practice precision-wise. It is better to keep all the terms in your sum with the same sort of orders of magnitudes.
Improved for correctness
import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
p=p*i
if(i%2!=0):
s=s-math.pow(x,i)/p
else:
s=s+math.pow(x,i)/p
print s
print math.exp(-x)
Note how the use of a for loop and less intermedis-ry sums makes it all easier to read.
Removing the branch
pow(-x,i) is negative if i is uneven, positive otherwise. Thus -pow(x,i) if i%2 != 0 else pow(x,i) can be rewritten pow(-x,i). Removing an if in an inner loop is (almost ?) always a good thing, for performance. So a simplified version is :
import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
p=p*i
s=s+math.pow(-x,i)/p
print s
print math.exp(-x)
That also has the benefit of making the code shorter (and thus more readable).
import math #imported to use the factorial function
def exp(x,n):
ans = 1 #initializing it with 1 because the first term is a constant:1
for i in xrange(1,n+1): #starts looping from 1 to n terms
ans+=(-1**i*(float(x)**i)/math.factorial(i)) #changing the sign of 1, adding.
# -1**i equals to 1 if i is even and -1 if i is odd
# ** operator stands for the pow() function , (2**3 =8)
# float(x) returns a floating value if value of x entered is integer
# You can remove this is you are already entering floating values.
# math.factorial() returns factorial of a given argument,
return ans
If you don't want to use the math.factorial() then you can try :
def exp(x,n):
ans = 1
dummy_factorial = 1
for i in xrange(1,n+1):
dummy_factorial*=i
print dummy_factorial
ans+=(-1**i*(float(x)**i)/(dummy_factorial))
return ans

Find the greatest common divisor

def gei(a, b):
'''
a, b: only positive integers! If you don't, we will make you. Max 1337
For extracting the juice of the numbers in the form of a common divider
'''
#Not Ruby, no to_i, but int()
smallest = int(abs(min(a, b)))
biggest = int(abs(max(a, b)))
print "You inputed: ", smallest, " and ", biggest, " their order doesn't matter."
print "Do you want to see guess numbers? Type 'yes', if you do! "
selection = raw_input()
print
print
#To evade infinite loops and too big numbers, we use count.
count = 0
ans = smallest
truth = str(selection) == str('yes')
def condition(ans, base):
ans1 = base % ans == 0
return ans1
while condition(ans, biggest) == False or condition(ans, smallest) == False:
ans -= 1
count += 1
if count >= 1337:
break
elif truth == True:
print ans
if truth == True:
print
print
print "After weeks of calculation, here is your greater common divider: "
return ans
So yeah, 8th grade informatics assignment to extract common greater dividers. I was wondering, maybe you guys know how can I make it less cumbersome? How to avoid using definition inside and naming so many variables?
import fractions
print fractions.gcd(4,8)
>>> 4
But you can also look at the source:
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
Reference: http://en.wikipedia.org/wiki/Euclidean_algorithm
Use Euclid's algorithm
int GCD(int a,int b){
if(b==0){
return a;
}
return GCD(b,a%b);
}
A few things can be improved in your code.
First off, truth is a truly poor variable name, since it doesn't really tell you what it's contents mean. I'd use something like show_work instead.
Next, you have an internal function that tells you a variable divides another evenly (returning a Boolean value). I'd suggest just using the modulus value directly, rather than coverting it to a bool with == 0, and you also don't need it to be in a function. Also, it's never necessary to compare a value to True or False. Just use the value itself (or use not to invert it). Putting these together will make your while loop's condition not biggest % ans and not smallest % ans.
Finally, you can use a better algorithm than trying every value one by one. Euclid's algorithm is a great way to calculate the Greatest Common Divisor quickly, and it's very easy to implement in Python (but I'll leave it to you).
This is nice an consise, and names no variable:
def gcd(a,b):
return max(d for d in xrange(1, min(a, b)+1) if a % d == b % d == 0)
print gcd(15, 25)
>>> 5
But please don't claim it as your own :)

Categories

Resources