python - 如何在 Python 中执行二分法

标签 python algorithm python-3.x bisection

我想编写一个 Python 程序来运行二分法来确定根:

f(x) = -26 + 85x - 91x2 +44x3 -8x4 + x5

二分法是一种用于估计多项式 f(x) 的根的数值方法。

是否有任何可用的伪代码、算法或库可以用来告诉我答案?

最佳答案

基本技术

下面是一些显示基本技术的代码:

>>> def samesign(a, b):
        return a * b > 0

>>> def bisect(func, low, high):
    'Find root of continuous function where f(low) and f(high) have opposite signs'

    assert not samesign(func(low), func(high))

    for i in range(54):
        midpoint = (low + high) / 2.0
        if samesign(func(low), func(midpoint)):
            low = midpoint
        else:
            high = midpoint

    return midpoint

>>> def f(x):
        return -26 + 85*x - 91*x**2 +44*x**3 -8*x**4 + x**5

>>> x = bisect(f, 0, 1)
>>> print(x, f(x))
0.557025516287 3.74700270811e-16

公差

要在达到给定容差时提前退出,请在循环末尾添加一个测试:

def bisect(func, low, high, tolerance=None):
    assert not samesign(func(low), func(high))   
    for i in range(54):
        midpoint = (low + high) / 2.0
        if samesign(func(low), func(midpoint)):
            low = midpoint
        else:
            high = midpoint
        if tolerance is not None and abs(high - low) < tolerance:
            break   
    return midpoint

关于python - 如何在 Python 中执行二分法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392208/

相关文章:

algorithm - 证明一组点中最远的点(在二维平面中)应该位于凸包上

python - 如何匹配句子中的字符串

python-3.x - 如何摆脱 Python Pandas 中的斜体并获取纯文本?

python - Pyinstaller,名称错误 : global name 'quit' is not defined

python - 如何替换 pandas 中的列名称但基于字典?

python - pandas 教程中的 Figsize() 函数

c# - 在 3D 场景中隐藏遮挡玩家的物体

python: += s, 中的逗号有什么作用?

algorithm - 递归和迭代的运行时间

database - 将列表成对并使用 sqlite3 将它们写入 .db 文件