Python中的二等分方法

时间:2018-10-25 18:50:22

标签: python

我正在用Python编写二等分方法。我在例程中设置了容错范围。我有两个问题:

  1. 我的函数应该能够找到任意连续标量值函数的根。如何将其传递给bisection_method并正确使用?
  2. 如何记录达到指定公差所需的迭代次数?

代码:

def f(x):
    return(x**2 - 11)

def bisection_method(a, b, tol):
    if f(a)*f(b) > 0:
        #end function, no root.
        print("No root found.")
    else:
        while (b - a)/2.0 > tol:
            midpoint = (a + b)/2.0
            if f(midpoint) == 0:
                return(midpoint) #The midpoint is the x-intercept/root.
            elif f(a)*f(midpoint) < 0: # Increasing but below 0 case
                b = midpoint
            else:
                a = midpoint
        return(midpoint)

answer = bisection_method(-1, 5, 0.0001)
print("Answer:", answer)

给出以下输出:

Answer: 3.31671142578125

1 个答案:

答案 0 :(得分:1)

对于函数,只需将函数名称作为参数传递即可。我已将您函数的名称更改为root11,并将其作为二等分的第一个参数。

为计数...您应该已经能够在线查询此内容。只需像学习for语句之前那样计算迭代次数即可。返回最终答案。

请注意,我删除了您的支票以得到确切的答案:无论如何,您将在下一次迭代中找到它。

def root11(x):
    return(x**2 - 11)

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(root11, -1, 5, 0.0001)
print("Answer:", answer, "\nfound in", iterations, "iterations")

import math
answer, iterations = bisection_method(math.cos, 0, 2, 0.0001)
print("Answer:", answer, "\nfound in", iterations, "iterations")

输出:

Answer: 3.31671142578125 
found in 15 iterations
Answer: 1.5706787109375 
found in 14 iterations