Python-使用线性搜索和对分搜索计算n次根

Python-使用线性搜索和对分搜索计算n次根,python,python-2.7,bisection,Python,Python 2.7,Bisection,我编写了两个函数来计算一个数字的第n个根。一个使用线性搜索,另一个使用对分搜索。 然而,当我试着给他们打电话时,他们俩都出现了问题。它只是说我指定的数字不能带到那个根。我很困惑,说不出我想说什么 我做错了。有人有主意吗 def rootBisect(root, num): low = 0.0 high = num ans = (high + low)/2.0 while ans ** root < abs(float(num)): if an

我编写了两个函数来计算一个数字的第n个根。一个使用线性搜索,另一个使用对分搜索。 然而,当我试着给他们打电话时,他们俩都出现了问题。它只是说我指定的数字不能带到那个根。我很困惑,说不出我想说什么 我做错了。有人有主意吗

def rootBisect(root, num):
    low = 0.0
    high = num
    ans = (high + low)/2.0
    while ans ** root < abs(float(num)):
        if ans ** root < num:
            low = ans
        else:
            high = ans
        ans = (high + low)/2.0
    if ans ** root != abs(num):
        print '%d cannot be taken to %d root.' % (num, root)
    else:
        if num < 0:
            ans = -ans
        print '%d root of %d is %d.' % (root, num, ans)
    return ans

def rootLinear(root, num):
    ans = 0
    while ans ** root < abs(float(num)):
        ans += 0.1
    if ans ** root != abs(num):
        print '%d cannot be taken to %d root.' % (num, root)
    else:
        if num < 0:
            ans = -ans
        print '%d root of %d is %d.' % (root, num, ans)
    return ans

rootBisect(2, 16)

rootLinear(2, 16)
def rootBisect(根,num):
低=0.0
高=num
ans=(高+低)/2.0
当ans**root
问题在于您希望
ans**root==abs(num)
为真。这是不可能的,因为浮点运算的精度有限。请看一看:

>>> import math
>>> math.sqrt(7)
2.6457513110645907
>>> math.sqrt(7)**2
7.000000000000001
>>> math.sqrt(7)**2 == 7
False
你应该改变你的成功条件。例如:

acceptable_error = 0.000001
if abs(ans ** root - abs(num)) <= acceptable_error):
    # success

我希望这是一个更清晰、更简单的代码

好的。。。但是如果将float(num)更改为int(num),它仍然会给出相同的答案,只是因为在这种情况下,将float转换为整数会意外地消除错误。
math.sqrt(3)**2
给出
2.99999999999996
,,如果我把ans+=0.1改成ans+=1,它会工作,但不是很准确,我不知道如何修正二等分法。另外,在while循环之后添加
ans=int(ans)
也没有用。我没有说你应该这样做
ans=int(ans)
。你应该接受不准确的答案。好主意。谢谢你的帮助!你认为num可能是负数吗?然后包括根(3,-8)、根(3,-0.125)和根(4,-16)等测试用例。前两个应该给出一个结果,最后一个只有复数根,因此应该在开始循环之前捕获。
while abs(ans ** root - abs(num)) > acceptable_error):
    ...
num1=input("Please enter a number to find the root: ")#accepting input and saving in num1
num2=input("Please enter another number as the root: ")#accepting input and saving in num2
x=float(num1)#converting string to float
n=float(num2)#converting string to float

least=1#the lower limit to find the average
most=x#the lower limit to find the average

approx=(least+most)/2#to find simple mean using search method taught in class

while abs(approx**n-x)>=0.0000000001:#for accuracy

    if approx**n>x:
        most=approx
    else:
        least=approx

    approx=(least+most)/2

print("The approximate root: ",approx)#output