用二分法求数的平方根

2024-05-17 12:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着找出一个数的平方根

 abs(y**2-x) < epsilon 

然而,使用二分法,我在运行它时没有得到想要的答案。如果我选择x为4和0.01,我期望得到2,但是相反,我得到1.0。有人能帮我修一下吗?你知道吗

测试用例:

 > squareRoot(4, 0.01)
 > 1.0
def squareRoot(x, epsilon):
    low = 0
    high = max(1.0, x)
    y = (high+low) / 2.0
    while abs(y**2 - x)<epsilon:
        if y**2 < x:
            low = y
        else:
            high = y
        y = (high + low) / 2.0
    return y

Tags: 答案returnifdef测试用例abselsemax
1条回答
网友
1楼 · 发布于 2024-05-17 12:36:55

你的while条件已经翻转了不等式。如果你已经找到了一个足够好的答案,你只能修改y。在伪代码中,您需要执行以下操作。你知道吗

def squareRoot(x, epsilon):
  <set up the base case>
  while <you haven't found the answer yet>:
    <bisect to keep looking for the answer>
  return <the answer>

将其与代码当前的功能进行比较。你知道吗

def squareRoot(x, epsilon):
  <set up the base case>
  while <you have found the answer>:
    <bisect to keep looking for the answer>
  return <the answer>

对代码进行一个字符的修改,给出正确的解决方案,如下所示。你知道吗

def squareRoot(x,epsilon):
    low = 0
    high = max(1.0,x)
    y = (high+low)/2.0
    while abs(y**2-x)>=epsilon:
        if y**2 < x:
            low = y
        else:
            high = y
        y = (high+low)/2.0
    return y

相关问题 更多 >