How to define new variable as float? - python

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)!")

Related

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

Print a whole number if the answer is whole, else print the float [duplicate]

This question already has answers here:
How to show decimal point only when it's not a whole number?
(3 answers)
Closed 2 years ago.
What's the shortest, most pythonic way to print out an integer if the result of an operation is an integer, otherwise print the float? Example:
def calc(x, y):
return (x / y)
How can I make sure that if the output of the function is a whole number, then print it as an integer, and if otherwise print it as a float? I know I can use is_integer() and build an if else statement, but is there a shorter, more pythonic way to do that?
Your function doesn’t print anything; it returns a value. That means it itself doesn’t have any control over the specifics of string formatting except by varying the type it returns. Maybe that’s what you want, a function that returns an int when the exact result is an integer and a float otherwise:
def calc(x, y):
# if x is divisible by y
if x % y == 0:
# integer division, producing an exact int result
return x // y
else:
# floating-point division, producing an approximate float result
return x / y
It’s a little weird to have variable return types, but this function could have its uses. Keep in mind that you can still get a float out of this with a zero fractional part (i.e. one that would be printed by default as “something.0”) if the fractional part is close enough to zero; calc(10**100, 10**100-1), for example. There are also results too big to represent as floats that will end up producing floating-point infinity.
Or maybe instead you always want to do floating-point division, and your problem is purely one of formatting: you never want to see “.0”. That should be done separate from the calculation:
# remains the same
def calc(x, y):
return x / y
def format_without_zero(f):
if f.is_integer():
return str(int(f))
else:
return str(f)
# but you use the result differently
result = calc(10, 5)
print(format_without_zero(result))
Or maybe you want precise division all the time! In that case, you can create fractions.Fractions and figure out how you want to format them.
def calc(x, y):
return (x//y if x%y== 0 else x/y)
I hope it's cool! Note parentheses actually does nothing here. Maybe readability who knows

Python math division operation returns 0

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

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

Error converting miles to kilometers

I'm trying to learn python and am attempting to create a simple formula that converts miles to kilometers and returns some text with the conversion.
Here's what I have:
def mile(x):
z = x * 1.609344
print "%.2f" % z
x = float(raw_input("How many miles are you traveling? "))
z = mile(x)
print "That's about % kilometers." % z
Can someone explain why this doesn't work? I could definitely set up the mile function to print a sentence with the conversion, but I didn't want to do that.
Your function needs to return the result.
def mile(x):
z = x * 1.609344
return z
You have a couple of problems. The first is that your function does not return a value. When the line z = mile(x) is run, the mile(x) part will be replaced by whatever is returned by mile. The code you want is:
def mile(x):
z = x * 1.609344
return z
Note that it is irrelevant what variable you assign this to; it doesn't have to match the variable that is being returned. For example, both y = mile(x) and z = mile(x) will assign to the given variable properly.
Second, your string formatting won't work. This is that part that looks like "That's about % kilometers." % z. The string formatting replaces %<identifier> with the given variable, where <identifier> tells what type the variable is (and possibly some info about how to display it). You will need the identifier f or, like in the earlier print statement, .2f, giving "That's about %.2f kilometers." % z
As way of an explanation:
You need to return the value of your computation/conversion from the function so that the result can be assigned to variable z. You can then print it out.
Before, you were printing the value inside your function, and not returning anything, which resulted in z getting assigned None which is why your print at the bottom didn't work.
In general it's best to do your work/computations inside the function and then return a value that you can decide how to use.
#wim shows the correct code for the function. If you now do
z = mile(x)
print "That's about %.2f kilometers." % z
you'll get the result you were expecting. (note the correct formatting as pointed out by #Aaron Dufour, you'll get 2 numbers past behind the decimal point when you print your result) Incidentally, your first print statement was correct, only the 2nd one was missing the complete formatting directive.

Categories

Resources