【发布时间】:2018-11-05 03:37:08
【问题描述】:
在以下代码中,我在 Python 中实现了二分法。作为一般概述,我的代码执行以下操作:
- 我的函数能够找到任意连续标量值函数 f 的根,作为 lambda 函数和规定的函数容差。
- 我的例程在区间 [0,1] 上找到函数 f(x) = cos x - sin x 的根,公差为 10^{-14}
- 记录达到此容差所需的迭代次数。
但是现在我希望在同一时间间隔上绘制收敛图。这将是作为迭代次数函数的绝对误差。
为此,我必须在一个列表中收集一系列错误数字,并将其与整数 1 的列表进行对比,直到您的 iter 的最终值。
当我遇到困难时,我正在寻求一些帮助。我已经用不同的迭代方法制作了另外 2 个代码,所以一旦我看到它在这个代码上是如何工作的,我应该也能够在其他代码上实现它!非常感谢所有帮助
import math
def root(x):
return(math.cos(x)-math.sin(x))
def bisection_method(f, a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
iter = 0
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(a)*f(midpoint) < 0: # Increasing but below 0 case
b = midpoint
else:
a = midpoint
iter += 1
return(midpoint, iter)
answer, iterations = bisection_method(root, 0, 1, 10**(-14))
print("Answer:", answer, "\nfound in", iterations, "iterations")
【问题讨论】:
-
您使用的是什么图形/绘图库?请edit您的问题并展示您自己的使用尝试。
-
绝对错误,还是答案?
-
绝对错误。
-
@martineau 我不知道如何开始!
-
但感谢您的编辑
标签: python