DIR Return Create A Forum - Home
---------------------------------------------------------
Essentials of Scientific Computing 2013
HTML https://esc2013.createaforum.com
---------------------------------------------------------
*****************************************************
DIR Return to: Programming Questions
*****************************************************
#Post#: 7--------------------------------------------------
Numerical Integration II
DIR By: mathnathan
Date: July 11, 2013, 8:30 am
---------------------------------------------------------
Here is the program we wrote in class together on Wednesday...
It is also attached to this post for you to download.
--- Code ---
#include <stdio.h>
#include <cmath>
double lhrIntegrate( int n, float a, float b );
double f( float x );
int main() {
float a = 2;
float b = 6;
double val;
double answer = 32.0/3.0;
double minErr = 1000;
double err;
int optimalN;
double optimalVal;
for( int n = 0; n < 5000; n++ ) {
if( n%100 == 0 ) {
printf( "On iteration %d\n", n );
}
val = lhrIntegrate( n, a, b );
err = std::abs(answer-val);
//printf( "val = %f\n", val );
//printf( "answer = %f\n", answer );
//printf("err = %f\n", err);
if( err < minErr ) {
minErr = err;
optimalN = n;
optimalVal = val;
}
}
printf( "integral value = %f\n", val );
printf( "minimum err = %f\n", minErr );
printf( "Optimal n = %d\n", optimalN );
printf( "Optimal val = %f\n", optimalVal );
return 0;
}
double f( float x ) {
return 4.0-(x-4.0)*(x-4.0);
}
double lhrIntegrate( int n, float a, float b ) {
//printf( "n = %d\n", n );
//printf( "a = %f\n", a );
//printf( "b = %f\n", b );
double sum = 0;
float step = (b-a)/n;
float xi = a;
for( int i = 0; i < n; i++ ) {
//printf("Iteration %d\n", i );
//printf("\txi = %f\n", xi);
//printf("\tarea = %f\n", step*f(xi));
sum += step*f(xi);
//printf("\ttotal sum = %f\n", sum );
xi += step;
}
return sum;
}
--- End Code ---
*****************************************************
Page 1 of 1