is_perfect 是一种检查数字是否具有完美 n 次根的方法。
例如:
- is_perfect(125,3)应该返回True,因为 5^3 是 125 一个整数
- is_perfect(126,3)应该返回False,因为没有 M^3 是整数的整数 M
def is_perfect(num,power):
root = 0.00
p = 0.00
float(p)
p = 1.0/power
root = num**(p)
print ("root",root,sep = ' ')
print ("root**power",root**power,sep = ' ')
check = num -(root**power)
print (check)
if check < 1e-14:
root = math.ceil(root)
if (root-int(root)) ==0:
print(num,root,int(root),p,sep = ' ')
return True
else:
print(num,root,int(root),p,sep=' ')
return False
在 Python shell 中,当 125 的结果应该为真时,两者都给出 False。
>>> is_perfect(126,3)
root 5.0132979349645845
root**power 125.99999999999999
1.4210854715202004e-14
126 5.0132979349645845 5 0.3333333333333333
False
>>> is_perfect(125,3)
root 4.999999999999999
root**power 124.99999999999993
7.105427357601002e-14
125 4.999999999999999 4 0.3333333333333333
False
>>>
如何修改我的方法以达到预期的结果。