How to do the Bisection method in Python

前端 未结 7 2414
小蘑菇
小蘑菇 2021-02-15 15:05

I want to make a Python program that will run a bisection method to determine the root of:

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

The Bisecti

7条回答
  •  我在风中等你
    2021-02-15 15:29

    With tolerance:

    # there is only one root
    def fn(x):
     return x**3 + 5*x - 9
     # define bisection method
    def bisection( eq, segment, app = 0.3 ):
     a, b = segment['a'], segment['b']
     Fa, Fb = eq(a), eq(b)
     if Fa * Fb > 0:
      raise Exception('No change of sign - bisection not possible')   
     while( b - a > app ): 
      x = ( a + b ) / 2.0
      f = eq(x)
      if f * Fa > 0: a = x
      else: b = x  
     return x
     #test it
    print bisection(fn,{'a':0,'b':5}, 0.00003) # => 1.32974624634
    

    Live: http://repl.it/k6q

提交回复
热议问题