I am working on an adaptive simpsons quadrature program and I am having issues with an if else statement. It seems like the computer is just skipping the logical statement. I have no idea why it isn't working - maybe I have been looking at it too long. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Adaptive Simpson Quadrature algorithm. There are two command ling arguments.
command line arugments: epsilon recursion_lim
Default command line arguments: .0001 5
Author: waterborne
Date: 1/24/2010
*/
float SimpsonQuad( float A, float B, float epsilon, int recursion_lim);
float f( float x);
int main (int argc, const char * argv[]) {
/* Constant Declarations */
float epsilon; // Tolerance
int recursion_lim; // Recursion depth limit
float I; // Approximation
/* Constant Definitions */
if (argv[1] == NULL) { // Set epsilon
epsilon = .0001;
printf("epsilon set to default.\n");
}
else {
epsilon = strtod( argv[1], NULL);
printf("epsilon set to %f\n", epsilon);
}
if (argv[2] == NULL) { // Set recursion limit
recursion_lim = 5;
printf("Recursion limit set to default.\n");
}
else {
recursion_lim = strtod( argv[2], NULL);
printf("Recursion limit set to %d\n", recursion_lim);
}
I = SimpsonQuad(0, 1, epsilon, recursion_lim);
printf("Approximation: %f\n", I);
return 0;
}
float SimpsonQuad( float A, float B, float epsilon, int recursion_lim){
/* Constant Declarations */
float h; // Mesh size
float alpha, beta, gamma; // Recursion nodes
float I_1, I_1a, I_1b, I_2; // Sub-integral values
float dif;
/* Constant Definitions */
h = (B - A) / 2.0;
alpha = A;
beta = B;
gamma = (alpha + beta) / 2.0;
/* Adaptive Algorithm */
I_1 = (h / 3.0) * (f(alpha) + 4.0 * f(gamma) + f(beta));
I_1a = (h / 3.0) * (f(alpha) + 4.0 * f((alpha + gamma) / 2.0) + f(gamma));
I_1b = (h / 3.0) * (f(gamma) + 4.0 * f((gamma + beta) / 2.0) + f(beta));
I_2 = I_1a + I_1b;
printf("I_1: %f, I_2: %f\n", I_1, I_2);
printf("count: %d\n", recursion_lim);
printf("dif: %f\n", fabs(I_2 - I_1));
dif = I_2 - I_1;
if (( fabs(dif) < epsilon) || (recursion_lim == 0)) {
return I_2;
}
else {
I_1a = SimpsonQuad( alpha, gamma, epsilon / 2.0, recursion_lim - 1);
I_1b = SimpsonQuad( gamma, beta, epsilon / 2.0, recursion_lim - 1);
I_1 = I_1a + I_1b;
printf("I: %f\n", I_1);
return I_1;
}
}
float f( float x){
float y = pow(x, 5);
return y;
}
The printf statements are there mainly to help me debug the program. If I run it with a recursion limit of 5, for example, the program will hit recursion_lim = 0 and keep on recurring even though the if statement tells it to return. I am not that experienced of a c programmer so maybe I am missing something simple. Thanks in advance!