1

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

2 回答 2

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):
    ...
于 2014-03-08T08:07:49.733 回答
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

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

于 2020-02-13T17:21:28.983 回答