Python - 使用线性和二等分搜索计算第n个根

时间:2014-03-08 07:35:48

标签: python python-2.7 linear bisection

我编写了两个函数来计算数字的第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)

2 个答案:

答案 0 :(得分:0)

问题在于您希望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

如果您的线性搜索需要很大的步骤,那么acceptable_error也必须很大。

关于二进制搜索,你应该有:

while abs(ans ** root - abs(num)) > acceptable_error):
    ...

答案 1 :(得分:0)

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

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