Advertisement
Guest User

Untitled

a guest
Jan 26th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. clear all
  2.  
  3. F = @(x) x.^cos(x);
  4.  
  5. %CAŁKI
  6. a=0;
  7. b=10;
  8.  
  9. X = [a:0.01:b];
  10. Y = F(X);
  11.  
  12. F_integral = integral(F, a, b);
  13. sprintf('Wbudowana funkcja integral: %d', F_integral)
  14.  
  15. %Metoda prostokątów
  16. n = 10;
  17. x = linspace(a,b,n+1);
  18. h = (b-a)/n;
  19.  
  20. F_rect = 0;
  21. for i=1:length(x)-1
  22. F_rect = F_rect + F(x(i));
  23. end
  24. F_rect = F_rect * h;
  25. sprintf('Metoda prostokątów: %d', F_rect)
  26.  
  27. %Metoda trapezów
  28. F_trap = 0;
  29. for i=2:length(x)-1
  30. F_trap = F_trap + F(x(i));
  31. end
  32. F_trap = (F_trap + (F(x(1)) + F(x(n+1)))/2) * h;
  33. sprintf('Metoda trapezów: %d', F_trap)
  34.  
  35. %Metoda Simpsona
  36. even = 0;
  37. for i=2:2:n
  38. even = even + F(x(i));
  39. end
  40. odd = 0;
  41. for i=3:2:n-1
  42. odd = odd + F(x(i));
  43. end
  44. F_simp = (F(a) + 4*even + 2*odd + F(b)) * (h/3);
  45. sprintf('Metoda Simpsona: %d', F_simp)
  46.  
  47. %Monte Carlo
  48. N = 10000;
  49. x = b * rand(N, 1);
  50. y = max(Y) * rand(N, 1);
  51.  
  52. z = y(y<=F(x));
  53. figure(1)
  54. fplot(F, [0 10])
  55. hold on
  56. for i=1:N
  57. if y(i) <= F(x(i))
  58. plot(x(i),y(i),'og')
  59. else
  60. plot(x(i),y(i),'or')
  61. end
  62. end
  63. F_monte = (length(z)/N) * (b-a) * (max(Y)-min(Y));
  64.  
  65. sprintf('Metoda Monte Carlo: %d', F_monte)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement