Search code examples
pythonmathfractions

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 number. 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


Solution

  • 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