Advertisement
VXP

ASD10_Integr_Trap_Simpson

VXP
May 8th, 2015
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. // ASD10_Integr_Trap.cpp: определяет точку входа для консольного приложения.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <math.h>
  7. using namespace std;
  8.  
  9. double f(double x)
  10. {
  11. return 2*log(cos(x)+2)-1;
  12. }
  13.  
  14. double trap(double a, double b, int n)
  15. {
  16. double h = (double)(b-a)/n, s = 0;
  17. for(int i = 1; i <= n-1; i++)
  18. {
  19. s += f(a+i*h);
  20. }
  21. return h * (f(a) + f(b))/2 + s;
  22. }
  23.  
  24. double simpson(double a, double b, int n) // чётное n => результат менее точный
  25. {
  26. double h = (b-a)/n, s = 0;
  27. for(int i = 1; i <= n-2; i += 2)
  28. {
  29. s += (2 * f(a+i*h) + 4*f(a+(i+1)*h))/3;
  30. }
  31. return h * ((f(a) + f(b))/2 + s);
  32. }
  33.  
  34. int _tmain(int argc, _TCHAR* argv[])
  35. {
  36. int n = 10;
  37. double a = 0, b = 100;
  38. double result = trap(a, b, n);
  39. cout << "Trap (n = " << n << "): " << result << endl;
  40. n = 11;
  41. result = simpson(a, b, n);
  42. cout << "Simpson (n = " << n << "): " << result << endl;
  43. cout << endl;
  44.  
  45. n = 20;
  46. result = trap(a, b, n);
  47. cout << "Trap (n = " << n << "): " << result << endl;
  48. n = 21;
  49. result = simpson(a, b, n);
  50. cout << "Simpson (n = " << n << "): " << result << endl;
  51. cout << endl;
  52.  
  53. n = 50;
  54. result = trap(a, b, n);
  55. cout << "Trap (n = " << n << "): " << result << endl;
  56. n = 51;
  57. result = simpson(a, b, n);
  58. cout << "Simpson (n = " << n << "): " << result << endl;
  59. cout << endl;
  60.  
  61. system("PAUSE");
  62. return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement