首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python中使用二等分方法

如何在Python中使用二等分方法
EN

Stack Overflow用户
提问于 2013-01-18 12:06:36
回答 8查看 60.6K关注 0票数 9

我想要做一个Python程序,它将运行一个二分法来确定根:

代码语言:javascript
运行
复制
f(x) = -26 + 85x - 91x2 +44x3 -8x4 + x5

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

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

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2013-01-18 15:50:28

基本技术

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

代码语言:javascript
运行
复制
>>> 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

容忍度

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

代码语言:javascript
运行
复制
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
票数 12
EN

Stack Overflow用户

发布于 2013-01-18 13:08:59

您可以在使用scipy.optimize.bisect的早期堆栈溢出问题here中看到解决方案。或者,如果您的目的是学习,Wikipedia entry on the bisection method中的伪代码是用Python语言实现自己的一个很好的指南,正如前面问题的评论者所建议的那样。

票数 6
EN

Stack Overflow用户

发布于 2018-03-23 21:36:01

我的实现比其他解决方案更通用,也更简单:(和公共领域)

代码语言:javascript
运行
复制
def solve(func, x = 0.0, step = 1e3, prec = 1e-10):
    """Find a root of func(x) using the bisection method.

    The function may be rising or falling, or a boolean expression, as long as
    the end points have differing signs or boolean values.

    Examples:
        solve(lambda x: x**3 > 1000) to calculate the cubic root of 1000.
        solve(math.sin, x=6, step=1) to solve sin(x)=0 with x=[6,7).
    """
    test = lambda x: func(x) > 0  # Convert into bool function
    begin, end = test(x), test(x + step)
    assert begin is not end  # func(x) and func(x+step) must be on opposite sides
    while abs(step) > prec:
        step *= 0.5
        if test(x + step) is not end: x += step
    return x
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14392208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档