Hey guys, I have looked around and am having trouble figuring out why my program is not integrating the function correctly. Here is my program and a sample of the output.
Code:
#include <stdio.h> //for use of the standard i/o functions
#include <stdlib.h> //for use of the standard library functions
#include <math.h> //for use of the math functions
double function(double x) //prototype for passing a number into the function
{
return exp(-x*x); //the hardcoded function e to the -x squared
}
double simpson(double a, double b, int c) //passing variables into the simpson function for evaluating simpsons rule
//a is the integrate to, b is the integrate from
//and c is the number of subdivisions
{
double dx = 1; //intial value of dx is 1 for the first pass of the for loop
int i = 0; //this variable is used for a 'for' loop as a counter and index position in the array
int n = 1; //this will be used as the multiplier to dx which increments based on the number of subdivisions
int j = 1;
int arr_length = ++c; //this array will hold the number of values calculated for the integration
double odd_sum = 0;
double even_sum = 0;
double total_sum = 0;
double answer_sum = 0;
double first_sum = 0;
double last_sum = 0;
dx = (b - a)/(c);
double arr_nums[arr_length]; //intialization of the array of numbers which will be summated for the integration
for(i = 1; i < --c; i++) //runs a for loop to evaluate the areas of the subdivisions of the function
{
arr_nums[i] = function(a + (dx * j));
j++;
}
if(n % 2 != 0 & n != c)
{
odd_sum = ((arr_nums[n]) * 4) + odd_sum;
n++;
n++;
}
n = 2;
if(n % 2 == 0)
{
even_sum = ((arr_nums[n]) * 2) + even_sum;
n++;
n++;
}
first_sum = function(a);
last_sum = function(b);
for(i = 0; i < c; i++)
{
total_sum = arr_nums[i] + total_sum;
}
total_sum = total_sum + first_sum + last_sum;
answer_sum = (dx / 3) * total_sum;
return answer_sum;
}
int main()
{
double integrate_from;
double integrate_to;
int num_of_subdivisions;
int temp_holder;
double answer;
printf("Integrate from: \n");
scanf("%lf", &integrate_from);
printf("Integrate to: \n");
scanf("%lf", &integrate_to);
printf("Number of subdivisions (must be a multiple of 2): \n");
scanf("%d", &num_of_subdivisions);
if(num_of_subdivisions % 2 != 0)
{
printf("That is not a multiple of 2");
exit(1);
}
else
{
// answer = simpson(integrate_from, integrate_to, num_of_subdivisions);
answer = simpson(integrate_from, integrate_to, num_of_subdivisions);
printf("%.10f\nThe integration is: ", answer);
}
}
Sample output:
Code:
C:\Users\askinne2\Desktop\Fall 2010\CS\Labs>simpson
Integrate from:
0
Integrate to:
3.14
Number of subdivisions (must be a multiple of 2):
6
0.3386618454