/* File: omp_trap.c * Purpose: Calculate definite integral using trapezoidal * rule. * * Input: a, b, n * Output: estimate of integral from a to b of f(x) * using n trapezoids. * * Compile: gcc -g -Wall -fopenmp -o trap_omp trap_omp.c * Usage: ./trap_omp * * Notes: * 1. The function f(x) is hardwired. * 2. This version uses OpenMP's parallel for with variable * scope specified, and static partitioning. */ #include #include #include #include #include "timer.h" int thread_count; void Usage(char* prog_name); double f(double x); /* Function we're integrating */ double Trap(double a, double b, int n); int main(int argc, char* argv[]) { double integral; /* Store result in integral */ double a, b; /* Left and right endpoints */ int n; /* Number of trapezoids */ double start, finish; if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1], NULL, 10); printf("Enter a, b, and n\n"); scanf("%lf", &a); scanf("%lf", &b); scanf("%d", &n); GET_TIME(start); integral = Trap(a, b, n); GET_TIME(finish); printf("With n = %d trapezoids, our estimate\n", n); printf("of the integral from %f to %f = %.15f\n", a, b, integral); printf("Elapsed time = %e seconds\n", finish - start); return 0; } /* main */ /*-------------------------------------------------------------------- * Function: Usage * Purpose: Print command line for function and terminate * In arg: prog_name */ void Usage(char* prog_name) { fprintf(stderr, "usage: %s \n", prog_name); exit(0); } /* Usage */ /*------------------------------------------------------------------ * Function: f * Purpose: Compute value of function to be integrated * Input arg: x * Return val: f(x) */ double f(double x) { double return_val; // return_val = x*x; return_val = sin(x); return return_val; } /* f */ /*------------------------------------------------------------------ * Function: Trap * Purpose: Use trapezoidal rule to compute definite integral * Input args: * a: left endpoint * b: right endpoint * n: number of trapezoids * Return value: Estimate of Integral from a to b of f(x) */ double Trap(double a, double b, int n) { double h, x, integral = 0; int i; h = (b-a)/n; integral += (f(a) + f(b))/2.0; # pragma omp parallel for schedule(static, 1) default(none) \ shared(a, h, n) private(i, x) \ reduction(+: integral) num_threads(thread_count) for (i = 1; i <= n-1; i++) { # ifdef DEBUG int my_rank = omp_get_thread_num(); printf("Thread %d > iter %d\n", my_rank, i); # endif x = a + i*h; integral += f(x); } integral = integral*h; return integral; } /* Trap */