Advertisement
labyyysosaaat

Untitled

Oct 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include<stdio.h>
  3. #include<math.h>
  4. using namespace std;
  5. /* Define the function to be integrated here: */
  6. double f(double x)
  7. {
  8. return x * x;
  9. }
  10.  
  11. /*Function definition to perform integration by Trapezoidal Rule */
  12. double trapezoidal(double f(double x), double a, double b, int n) {
  13. double x, h, sum = 0, integral;
  14. int i;
  15. h = fabs(b - a) / n;
  16. for (i = 1; i < n; i++) {
  17. x = a + i * h;
  18. sum = sum + f(x);
  19. }
  20. integral = (h / 2)*(f(a) + f(b) + 2 * sum);
  21. return integral;
  22. }
  23.  
  24. /*Program begins*/
  25. int main() {
  26. int n, i = 2;
  27. double a, b, h, eps, sum = 0, integral, integral_new;
  28.  
  29.  
  30. cout << "\nEnter the initial limit: ";
  31. cin >> a;
  32. cout << "\nenter the final limit: ";
  33. cin >> b;
  34. cout << "\nEnter the desired accuracy: ";
  35. cin >> eps;
  36. integral_new = trapezoidal(f, a, b, i);
  37.  
  38. /* Perform integration by trapezoidal rule for different number of sub-intervals until they converge to the given accuracy:*/
  39. do {
  40. integral = integral_new;
  41. i++;
  42. integral_new = trapezoidal(f, a, b, i);
  43. } while (fabs(integral_new - integral) >= eps);
  44.  
  45. /*Print the answer */
  46. cout << "The integral is: " << integral_new;
  47. cout << "with intervals:"<<i;
  48. system("pause");
  49. return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement