【问题标题】:Finding the square root of a number using bisection method用二分法求一个数的平方根
【发布时间】:2019-10-08 00:46:29
【问题描述】:

我试图找到一个数的平方根,使得

 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

【问题讨论】:

  • 什么意思?
  • 我认为您的while 条件是错误的。
  • 但是 abs(y**2-x) 必须小于 epsilon
  • 当然,但是当abs(y**2-x) 小于 epsilon 时,您应该返回。您不应该继续执行 while 循环并修改答案。
  • 你的意思是while abs(y**2-x) &gt; epsilon:???

标签: python bisection


【解决方案1】:

您的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

【讨论】:

  • 但是我必须找到 y 使得 abs(y**2-x) 必须小于 epsilon,尽管
  • 你需要继续循环while它是&gt;= epsilon...并且当这个表达式是False时停止循环。
  • 等等,我在哪里显示 abs(y**2)
  • abs(y**2-x) &gt;= epsilonFalse 这意味着abs(y**2-x) &lt; epsilon - 你可以停止循环并返回结果。 while循环在条件为True时执行,在条件为False时退出。
  • @deezy 和答案中的代码就是这样做的。想想&gt;=&lt;的关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多