Python: function to define a number, square, cube, etc.

My simple task is to create a function that determines if the number N can be written as a^n

for some given n, i.e. i need to check if N^(1/n)

an integer is. Somehow this function is giving wrong results:

def is_power(N, n):
    r = float(N) ** ( 1. / float(n) )
    return r.is_integer()

      

For n=2

he works.

For n=3

and N = 1,8,27, the function returns True, which is correct. But from now on False, for example. for 4*4*4=64

or 5*5*5=125

. How can I create a working function that will find numbers that are squares / cubes / etc?

+3


source to share


1 answer


Floating point arithmetic is not precise - see Is mathematics floating point? ...

So check your answer using exact integer math. Round r

to the nearest whole and then see if the power works. This Python 3 code removes some of your redundant types. For Python 2, end the computation r

to int()

typecast (which is not needed for Python 3).



def is_power(N, n):
    r = round(N ** (1.0 / n))
    return r**n == N

      

+6


source







All Articles