python - 具有循环递归的牛顿法
问题描述
我这里的代码都弄清楚了。指示说“将项目 1 中用于逼近平方根的牛顿方法转换为名为 newton 的递归函数。(提示:平方根的估计值应作为函数的第二个参数传递。)” 我将如何计算这些根据我的代码这里的方向?
# Initialize the tolerance
TOLERANCE = 0.000001
def newton(x):
"""Returns the square root of x."""
# Perform the successive approximations
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= TOLERANCE:
break
return estimate
def main():
"""Allows the user to obtain square roots."""
while True:
# Receive the input number from the user
x = input("Enter a positive number or enter/return to quit: ")
if x == "":
break
x = float(x)
# Output the result
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
if __name__ == "__main__":
main()
解决方案
本质上,您需要while True:
在递归函数中转换部分代码,如下所示:
def newton(x, estimate):
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference > TOLERANCE:
estimate = newton(x, estimate)
return estimate
注意条件是如何不同的,因此您检查是否需要继续,在您不需要最终值之后,将执行递归并返回
推荐阅读
- php - 使用 Google Drive API 将文件夹移动到团队云端硬盘
- c# - 与布尔值 false 进行比较时,如何防止 Linq2Sql 否定位列?
- c++ - 以 ac 样式数组为成员的结构的 rapidcheck 生成器
- python - 如何使用基于数据的函数扩展类并在编译时检查?
- c# - Razor 视图引擎何时将 IActionResult 转换为 HTML?
- javascript - 在使用邮递员测试基本的 Nodejs CRUD API 时,它给出了错误“无法发布”。如何解决这个问题?
- flutter - ChangeNotifierProvider:可以重新创建其创建的 ChangeNotifier 吗?
- mysql - MySql - 具有特定字段计数的列表
- ruby - 为什么 Ruby setter 返回传递的值,而不是实例变量的最终值?
- git - 在 Github 提交之前:你对文件管理的管家规则是什么?