Advertisement
Guest User

Untitled

a guest
May 30th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include "stdafx.h"
  2. #define _USE_MATH_DEFINES
  3. #include <iostream>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7.  
  8. double f(double x);
  9. double metoda_trapezow(double a, double b, int n);
  10. double metoda_simpsona(double a, double b, int n);
  11. double metoda_kwadratur(double a, double b, int n);
  12.  
  13. int main()
  14. {
  15. cout << metoda_trapezow(0, M_PI, 2000) << endl;
  16. cout << metoda_simpsona(0, M_PI, 1000) << endl;
  17. cout << metoda_kwadratur(0, M_PI, 400) << endl;
  18. return 0;
  19. }
  20.  
  21. double f(double x) {
  22. return sin(x);
  23. }
  24.  
  25. double metoda_trapezow(double a, double b, int n) {
  26. double h = (b - a) / n;
  27. double sum = 0;
  28. double podstawa_1 = f(a);
  29. double podstawa_2;
  30. for (int i = 0; i < n; i++) {
  31. podstawa_2 = f(a + h * i);
  32. sum += (podstawa_1 + podstawa_2);
  33. podstawa_1 = podstawa_2;
  34. }
  35. return 0.5 * sum * h;
  36. }
  37.  
  38. double metoda_simpsona(double a, double b, int n) {
  39. double h = (b - a) / n;
  40. double xi = a;
  41. double xi1, ti;
  42. double sum = 0;
  43. for (int i = 0; i < n; i++) {
  44. xi1 = a + i * h;
  45. ti = (xi + xi1) / 2;
  46. sum += ((xi1 - xi) / 6) * (f(xi) + f(xi1) + 4 * f(ti));
  47. xi = xi1;
  48. }
  49. return sum;
  50. }
  51.  
  52. double metoda_kwadratur(double a, double b, int n) {
  53.  
  54. int ng = 1;
  55. double h = (b - a) / (n - 1);
  56.  
  57. double psi[2];
  58. psi[0] = -sqrt(1 / 3); psi[1] = -psi[0];
  59. double w[2];
  60. w[0] = 1.0; w[1] = 1.0;
  61. double calka = 0; double sum = 0;
  62. double xi = a;
  63. double xi1;
  64. for (int i = 0; i < n; i++) {
  65. sum = 0;
  66. xi1 = a + i * h;
  67. for (int j = 0; j <= ng; j++) {
  68. psi[j] = ((xi1 - xi) / 2) * f((xi1 + xi) / 2 + (xi1 - xi) / 2 * psi[j]);
  69. sum += psi[j] * w[j];
  70. }
  71. xi = xi1;
  72. calka += sum;
  73. }
  74.  
  75. return calka;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement