Advertisement
Guest User

Untitled

a guest
Oct 19th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Oct 19 11:22:10 2017
  4.  
  5. @author: student
  6. """
  7.  
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import scipy.optimize as opt
  11.  
  12. def f(x):
  13. #return 2.0*x**2-4.0
  14. return np.cos(10*x)
  15.  
  16. #a = input('unesi lijevu granicu: ')
  17.  
  18. xl = 0
  19. #xl = float(a)
  20. #xl = float(input('unesi lijevu granicu: '))
  21. xd = 0.4
  22. print(f(xl), f(xd))
  23.  
  24. plt.plot([xl], [f(xl)], 'ob') #zahtjevaju listu brojeva pa su u [], iako je to lista koja
  25. plt.plot([xd], [f(xd)], 'ob') #ima samo jedan clan
  26.  
  27. it = 0
  28.  
  29. while it < 30:
  30. xs = (xl+xd)/2
  31. plt.plot([xs], [f(xs)], 'or') #or je Red, ob je Blue
  32. plt.annotate(str(it), xy=[xs, f(xs)]) # str pretvara broj u string
  33. if abs(f(xs)) < 0.01:
  34. break
  35. #plt.annotate(it, xy=[xs, f(xs)]) #annotate pise rijec (1) na poziciji (xy =...)
  36.  
  37. if f(xs)*f(xl) < 0:
  38. xd = xs
  39. else:
  40. xl = xs
  41. xs = (xl+xd)/2
  42. it += 1
  43.  
  44. #print('rjesenje: f({})={}'.format(xs, f(xs)) )
  45. print('x: ', xs)
  46. print('f(x): ', f(xs))
  47. print('it : ', it)
  48.  
  49. x_opt = opt.fsolve(f, 0)
  50. print(x_opt)
  51.  
  52. x_f = np.linspace(0, 0.4, 401) #0.4 u 30
  53. y_f = f(x_f)
  54.  
  55. plt.plot(plt.xlim(), [0, 0], color='red')
  56.  
  57. plt. plot(x_f, y_f)
  58.  
  59. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement