Serial-area

From Earlham Cluster Department

Revision as of 11:16, 2 August 2012 by Charliep (Talk | contribs)
Jump to: navigation, search

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>

const long long DEFAULT_NUMSEG = 1000;
const long double DEFAULT_STARTX = 0;
const long double DEFAULT_ENDX = 1;

// Hint - use inline to improve the performance of this function
long long min(long long x, long long y) {
	return (x < y ? x : y);
}

// This is the function "f" being integrated
long double f(long double x) {
	return(x * x);
}

// Sums the area of all the trapezoids together to estimate the integral
long double sum_intervals(long long numSeg, long double startX, long double endX) {
	long long i;
	long double area = 0;
	long double x1, x2;
	long double rangeX = endX - startX;
	long double deltaX = rangeX / numSeg;
	
	for (i = 0; i < numSeg; ++i) {
		x1 = startX + i * deltaX;
		x2 = startX + (i + 1) * deltaX;
		area += (f(x1) + f(x2)) * (long double).5 * deltaX;
	}

	return(area);
}

void print_usage() {
	fprintf(stderr, "Usage: area-serial [-s segments] [-o origin] [-e end]\n");
	return; 
}

int main( int argc, char **argv) {
	long long numSeg = DEFAULT_NUMSEG;
	int c;
	long double startX = DEFAULT_STARTX;
	long double endX = DEFAULT_ENDX;
	long double deltaX, area;

		// Parse command line arguments	
		while ((c = getopt (argc, argv, "s:o:e:h")) != -1)
			switch (c) {
				case 's':
					numSeg = atoll(optarg);
					break;
				case 'o':
					startX = atof(optarg);
					break;
				case 'e':
					endX = atof(optarg);
					break;
				case 'h':
					print_usage();
					return(EXIT_SUCCESS);
					break;
				case '?':
					if (optopt == 's' || optopt == 'o' || optopt == 'e')
						fprintf (stderr, "Option -%c requires an argument.\n", optopt);
					else if (isprint (optopt))
						fprintf (stderr, "Unknown option `-%c'.\n", optopt);
					else
						fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
				default:
					abort();
			}

		if ((numSeg < 1) || (startX >= endX)) {
			print_usage();
			exit(EXIT_FAILURE); 
		}

	// Allocate space for function values, calculate them, sum them, display the result
	area = sum_intervals(numSeg, startX, endX); 
	printf("Area under curve y = x^2 from %Lg to %Lg is %.18LG\n", startX, endX, area);

	return(EXIT_SUCCESS);
}
Personal tools
Namespaces
Variants
Actions
websites
wiki
this semester
Toolbox