【问题标题】:Solving equation using bisection method使用二分法求解方程
【发布时间】:2011-05-18 14:53:30
【问题描述】:

我可以在网上找到一种专门针对 python 的二分法吗?

例如,给定这些方程,我如何使用二分法求解它们?

x^3 = 9  
3 * x^3 + x^2 = x + 5  
cos^2x + 6 = x  

【问题讨论】:

  • 我希望我的数值方法课程使用 Python。 :/ 这对自己实现很有指导意义;只需阅读 Wikipedia 对算法的描述即可。
  • 最好使用许多人已经在使用的东西,而不是尝试自己编写。 75%-90% of binary search implementations are incorrect.

标签: python numerical-analysis bisection


【解决方案1】:

使用scipy.optimize.bisect

import scipy.optimize as optimize
import numpy as np

def func(x):
    return np.cos(x)**2 + 6 - x

# 0<=cos(x)**2<=1, so the root has to be between x=6 and x=7
print(optimize.bisect(func, 6, 7))
# 6.77609231632

optimize.bisect调用_zeros._bisect,用C实现。

【讨论】:

  • 如何获取a和b值?还有循环次数?
  • 就像在示例math.fullerton.edu/mathews/n2003/BisectionMod.html 中一样,它试图求解这个方程 (x^3+4x^2-10=0),它使用函数 Bisection[1,2,30] 如何得到数字 1 2 和 30?是方程吗?
  • @bn:要使用bisect,必须提供ab,这样func(a)func(b)的符号相反,从而保证@987654333中有根@ 因为func 需要是连续的。您可以尝试猜测ab 的值,使用一些分析,或者如果您想以编程方式进行,您可以设计一些生成候选ab 的方法,直到找到两个有相反的迹象。然而,这超出了简单的bisect 方法的范围。
  • @bn:关于迭代次数,scipy.optimize.bisect 有一个maxiter 参数。例如,so.bisect(func,6,8,maxiter=500)。见docs.scipy.org/doc/scipy/reference/generated/…
  • @unutbu,谢谢!对于 (equation x^3 = 9) 我尝试了 a 的 0 和 b (2.10571289062) 的 1000 的值。根据 wolfram,它给了我不同的答案,a 为 0,b 为 5(2.0802307129),这个 2.0802307129 是答案wolframalpha.com/input/?i=x^3+%3D+9++
【解决方案2】:

这对你有帮助!

import numpy as np

def fn(x):
    # This the equation to find the root
    return (x**3 - x - 1) #x**2 - x - 1

def find_root_interval():
    for x in range(0, 1000):
        if fn(x) < 0:
            lower_interval = x
            if fn(x+1) > 0:
                higher_interval = x + 1
                return lower_interval, higher_interval
    return False

def bisection():
    a,b = find_root_interval()
    print("Interval: [{},{}]".format(a,b))
    # Create a 1000 equally spaced values between interval
    mid = 0
    while True:
        prev_mid = mid
        mid = (a+b)/2
        print("Mid value: "+str(mid))
        # 0.0005 is set as the error range
        if abs(mid-prev_mid) < 0.0005:
            return mid
        elif fn(mid) > 0:
            b = mid
        else:
            a = mid

root = bisection()
print(root)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2016-04-09
    相关资源
    最近更新 更多