How do I pass a fraction to python as an exponent in order to calculate the nth root of an integer?
I'm attempting to write a simple python script that will calculate the squareroot of a numbe开发者_StackOverflowr. heres the code i've come up with and it works. but i would like to learn how to use fractional exponents instead.
var1 = input('Please enter number:')
var1 = int(var1)
var2 = var1**(.5)
print(var2)
thanks for the help
You can use fractional exponents with the help of fractions
module.
In this module there is a class Fraction
which works similar to our inbuilt int
class.
Here is a link to the documentation of the class - http://docs.python.org/library/fractions.html (just go through its first few examples to understand how it works. It is very simple.)
Heres the code that worked for me -
from fractions import Fraction
var1 = input('Please enter number:')
var1 = Fraction(var1)
expo = Fraction('1/2') //put your fractional exponent here
var2 = var1**expo
print var2
numerator, denominator = [float(s) for s in raw_input().strip().split("/")]
print 2 ** (numerator/denominator)
I strip whitespace from the input, split it into parts, then convert the parts to numbers with a list comprehension.
This will fail if the input isn't in fractional form. To check and behave appropriately...
line = raw_input().strip()
if "/" in line:
numerator, denominator = [float(s) for s in line.split("/")]
exponent = numerator/denominator
else:
exponent = float(line)
print 2 ** exponent
If you had tried using 2 ** (1/2)
and it had failed, that is because 1
and 2
are integers, so Python 2 uses integer division and ignores the fractional part. You could fix this by typing 1.0/2
into your script or input()
.
精彩评论