Advertisement
osipyonok

Inegration omp

May 29th, 2017
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. // integral_sequential.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <cmath>
  6. #include <ctime>
  7. #include <omp.h>
  8.  
  9. using namespace std;
  10.  
  11. double f(double x);
  12.  
  13. double rectangle_method(double a, double b, int n) {
  14.     double sum = 0;
  15.     double h = (b - a) / n;
  16.     int i;
  17.     double cur = 0 , x;
  18.     omp_set_num_threads(4);
  19. #pragma omp parallel for reduction(+:sum)
  20.     for (i = 0; i < n; ++i) {
  21.         x = a + h * i;
  22.         sum = sum + f(0.5 * (x + x + h));
  23.     }
  24.  
  25.     return sum * h;
  26. }
  27.  
  28. double rec_method_seq(double a, double b, int n) {
  29.     double h = (b - a) / n;
  30.     double sum = 0.0;
  31.     for (int i = 0; i < n; ++i) {
  32.         double x = a + h * (double)i;
  33.         sum += f(0.5 * (x + x + h));
  34.     }
  35.     return h * sum;
  36. }
  37.  
  38. double f(double x) {
  39.     return sin(x);
  40. }
  41.  
  42. inline void solve(double a, double b, int n) {
  43.     long long l = clock();
  44.     double ans = rectangle_method(a, b, n);
  45.     cout << "Parallel I(x) = " << ans << endl;
  46.     cout << "Parallel time: " << (double)(clock() - l) / CLOCKS_PER_SEC << endl << endl;
  47. }
  48.  
  49. inline void solve_seq(double a, double b, int n) {
  50.     long long l = clock();
  51.     double ans = rec_method_seq(a, b, n);
  52.     cout << "Sequential I(x) = " << ans << endl;
  53.     cout << "Sequential time: " << (double)(clock() - l) / CLOCKS_PER_SEC << endl << endl;
  54. }
  55.  
  56. int main(int argc, char** argv)
  57. {
  58.     cout.precision(5);
  59.     cout.setf(ios::fixed);
  60.     double a, b, n;
  61.     a = 0;
  62.     b = 10000;
  63.     n = 1e9;
  64.    
  65.     solve(a, b, n);
  66.  
  67.     solve_seq(a, b, n);//sequentival solve
  68.  
  69.  
  70.     system("pause");
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement