From Education
#include <stdio.h>
// This is intended to be a straightforward implementation of area under a curve
//
// Suggested modifications to scalar code:
// - actually use a trapezoidal approximation
// - calculate upper and lower rectangles for each segment and thus upper and lower bounds
// and thus error estimate
// - release restriction that function be monotonic increasing
//
// Suggested modifications to parallel code:
// - modify to be run under parallel method du jour: OpenMP/MPI/Cuda or hybrid combination of these
// - what happens when number of processes does not evenly divide number of segments
// - what happens to accuracy of solution as you increase the number of segments (any anomalies?)
// - what happens if you derive number of segments from a desired error bound
//
// (monotonic increasing) function to integrate
float func(float x){
return x*x;
}
int main() {
// constraints
int num_seg=1000; // number of segments
float start_x=0.0, end_x=1.0; // start and end of overall area
// variables
int i; // loop counter
float seg_width; // segment width
float low_x, low_y; // low endpoint of segment
float high_x, high_y; // low endpoint of segment
float area; // area of segment
printf("Hello\n");
// calculate the segment width
seg_width = (end_x-start_x)/num_seg;
printf("seg_width= %f\n", seg_width);
for (i=0; i<num_seg; ++i) {
low_x = (start_x + i * seg_width);
high_x = (start_x + (i+1) * seg_width);
low_y = func(low_x);
high_y = func(high_x);
area += seg_width * (low_y + high_y) * 0.5;
printf("i = %d, low_x = %f, high_x = %f, low_y = %f, high_y = %f, area = %f \n", i,
low_x, high_x, low_y, high_y, area);
}
}