Advertisement
Guest User

bisekcja

a guest
Nov 18th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. # The function is x - b - e^x
  2. def func(x):
  3.     return x + 2 - np.exp(x)
  4.    
  5. # Prints root of func(x)
  6. # with error of EPSILON
  7. def bisection(a,b):
  8.  
  9.     if (func(a) * func(b) >= 0):
  10.         print("You have not assumed right a and b\n")
  11.         return
  12.    
  13.     c = a
  14.     while ((b-a) >= 0.01):
  15.  
  16.         # Find middle point
  17.         c = (a+b)/2
  18.    
  19.         # Check if middle point is root
  20.         if (func(c) == 0.0):
  21.             break
  22.    
  23.         # Decide the side to repeat the steps
  24.         if (func(c)*func(a) < 0):
  25.             b = c
  26.         else:
  27.             a = c
  28.              
  29.     print("The value of root is : ","%.4f"%c)
  30.      
  31. # Driver code
  32. # Initial values assumed
  33. a =-1
  34. b =1
  35. bisection(a, b)
  36.  
  37. x = np.linspace(-5, 5, 100)
  38. plt.plot(x, func(x))
  39. plt.grid()
  40. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement