Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. from numpy.polynomial import Polynomial
  5.  
  6. f = Polynomial([2.0, 1.0, -6.0, -2.0, 2.5, 1.0])
  7. a = -0.5
  8. b = 1.3
  9. m = (a+b)/2
  10. e = 1e-6
  11.  
  12. list_a = []
  13. list_b = []
  14. list_m = []
  15. list_f = []
  16.  
  17. root = 0.0
  18.  
  19. #+----------------------+
  20. #| Start of your code +
  21. #+----------------------+
  22. while True:
  23. list_a.append(a)
  24. list_b.append(b)
  25. list_m.append(m)
  26. list_f.append(f(m))
  27. if f(a)*f(m)<0:
  28. b=m
  29. m=(a+b)/2
  30. list_m.append(m)
  31. list_a.append(a)
  32. list_b.append(b)
  33. list_f.append(f(b))
  34.  
  35. else:
  36. a=m
  37. m=(a+b)/2
  38. list_m.append(m)
  39. list_a.append(a)
  40. list_b.append(b)
  41. list_f.append(f(a))
  42.  
  43. if (abs(list_m[-1]-list_m[-2])/abs(list_m[-1]))<=e:
  44. root=m
  45. break
  46.  
  47. #+--------------------+
  48. #| End of your code +
  49. #+--------------------+
  50.  
  51. xs = np.linspace(-2.5, 1.6, 100)
  52. ys = f(xs)
  53.  
  54. plt.axhline(y=0, color='k')
  55. plt.plot(xs, ys)
  56. plt.plot(root, f(root), 'ro')
  57.  
  58. print(pd.DataFrame({'a':list_a, 'b':list_b, 'm':list_m, 'f(x)':list_f}))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement