-3
def findRoot1(x, power, epsilon):
    low = 0
    high = x
    ans = (high+low)/2.0
    while abs(ans**power - x) > epsilon:
        if ans**power < x:
             low = ans
        else:
             high = ans
        ans = (high+low)/2.0
    return ans



def findRoot2(x, power, epsilon):
    if x < 0 and power % 2 == 0:
        return None
#can't find even powered root of negative number
    low = min(0, x)
    high = max(0, x)
    ans = (high+low)/2.0
    while abs(ans**power-x) > epsilon:
        if ans**power < x :
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans


def findRoot3(x, power, epsilon):
    """x and epsilon int or float, power an int
          epsilon > 0 and power >= 1
          returns a float y s.t. y**power is within epsilon of x.
          if such a float does not exist, it returns None."""
    if x < 0 and power % 2 == 0:
        return None
#can't find even powered root of negative number
    low = min(-1, x)
    high = max(1, x)
    ans = (high+low)/2.0
    while abs(ans**power-x) > epsilon:
        if ans**power < x :
            low = ans
        else:
            high = ans
        ans = (high+low)/2.0
    return ans

为什么 findRoot1(-27.0, 3, 0.001) 在第一种情况下会失败?逻辑是如何形成的?

为什么 findRoot2(0.25, 3, 0.001) 在第二种情况下会失败?findRoot2(-27.0, 3, 0.001) 如何通过这里?

它适用于第三种情况。如何?

4

1 回答 1

1

案件的问题是——

  1. 第一种情况:你假设你得到的输入x总是正的,因为你总是将它设置为高,所以当发送一个负数时,ans在第一次迭代中是 -13.5,因为(-13.5)**3是负的,它总是小于 epsilon,因此,您将-13.5设置为low从那里开始,它会不断减小(在下一次迭代中变为-20.25)直到达到-27(即当低和高都变为-27时),然后它进入无限循环。

  2. 第二种情况:您没有处理数字小于 1 的情况,在这种情况下,该数字的幂会更小,例如x = 0.125, x^3 = 0.001953125。但是您对第二种情况的逻辑取决于ans**power始终大于x,这仅在x其本身大于 1 时才有效。同样,这会导致在第一次迭代后low设置为0.125,然后它继续增加直到low等于high= 0.25,在这种情况下,它进入无限循环。

  3. 第三种情况:它有效,因为您更改了设置条件lowhighans小于 1 并且它也处理负数。

于 2015-06-20T12:15:36.997 回答