python - 使用巴比伦方法求平方根返回错误值

标签 python python-3.x

尝试使用循环函数求数字的平方根。 我正在尝试使用巴比伦方法,但它不会返回正确的答案。如果有人能指出我哪里有错误,我将不胜感激。

def sqrt(number, guess, threshold):
    x = number / 2
    prev_x = x + 2 * threshold
    while abs(prev_x - x) > threshold:
        prev_x = x
        x = (x + guess / x) / 2
        square_root = x
        return square_root

test = sqrt(81, 7, 0.01)
print (test)

最佳答案

  1. 更改

    x = (x+猜测/x)/2

因为这将进展到猜测的平方根。将其更改为

x = (x+number/x)/2
  • 将 return 语句移出 while 循环

  • 初始化 x 来猜测而不是 number/2

  • 关于python - 使用巴比伦方法求平方根返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378408/

    相关文章:

    python - 尝试在 Windows 上导入 pymssql 时出现 "ImportError: DLL load failed"

    python - 无法从网页中获取一些分散的项目

    python - 如何在另一个 dag apache Airflow 中创建 dags

    python - 如何解析类属性的名称?

    python - 一次对两个元素进行分组

    python - 如何使用 wxpython 在 1 个应用程序中放置 2 个框架?

    python - 在Python中生成二进制的二维数组

    python - 用换行符写文本文件

    python - 切换服务器时过滤损坏的引用 Django 电子邮件

    python - python中的 boolean 列表操作