|
|
a = start of interval
b = end of interval
N = # segments
======================================
integral = 0.0
h = (b-a)/N
x = a
for i = 1 to N
{ integral = integral + f(x)*h
x = x + h
}
|
float f(float x)
{
return(x*x);
}
int main(int argc, char *argv[])
{
extern float f(float);
float a, b, h, x, integral;
int N, i;
cout << "Enter start of interval: ";
cin >> a;
cout << "Enter end of interval: ";
cin >> b;
cout << "Enter N (number of segments): ";
cin >> N;
integral = 0.0;
h = (b-a)/N; // Compute step size
x = a;
for (i = 1; i <= N; i = i + 1)
{
integral = integral + f(x)*h; // f(x) = f(a), f(a+h), f(a+2h)...
x = x + h; // x = a, a+h, a+2h, etc
}
cout << "Approximate finite integral = " << integral << "\n";
}
|
Example: the program cannot compute:
Integral( f(x) from a to b)
-------------------------------
Integral( g(x) from a to b)
|
|
(and combined together in the final program compilation)
// This function is
// CHANGED often
// -- keep separate
float f(float x)
{
return(x*x);
}
|
// The algorith
// does NOT CHANGED
// often
// Declare function f before its use !!!
extern float f(float);
int main(int argc, char *argv[])
{
float a, b, h, x, integral;
int N, i;
...input a, b, N
integral = 0.0;
h = (b-a)/N;
x = a;
for (i = 1; i <= N; i = i + 1)
{
integral = integral + f(x)*h;
x = x + h;
}
}
|
|
int main(int argc, char *argv[])
{
float a, b, h, x, integral;
int N, i;
...input a, b, N
// Algorithm is "stuck" in the main program
integral = 0.0;
h = (b-a)/N;
x = a;
for (i = 1; i <= N; i = i + 1)
{
integral = integral + f(x)*h;
x = x + h;
}
}
|
As the main program , it cannot be easily deployed in other programs.
| Implement well-defined task/operations as one or more functions |
Example:
int main(int argc, char *argv[])
{
float a, b, h, x, integral;
int N, i;
...input a, b, N
// Well-defined task implemented as a FUNCTION
integral = Rectangle_Rule(.....);
}
|
|
float RectangleRule(float f(float), float a, float b, int N)
{
float integral, h, x;
int i;
integral = 0.0;
h = (b-a)/N;
x = a;
for (i = 1; i <= N; i = i + 1)
{
integral = integral + f(x)*h;
x = x + h;
}
return(integral);
}
|
This example uses the knowledge about passing function as parameter discussed in this webpage: click here
// Declare function f
extern float f(float);
// Declare function RectangleRule
extern float RectangleRule(float f(float),
float, float, int);
int main(int argc, char *argv[])
{
float a, b, integral;
int N;
cout << "Enter start of interval: ";
cin >> a;
cout << "Enter end of interval: ";
cin >> b;
cout << "Enter N (number of segments): ";
cin >> N;
integral = RectangleRule(f, a, b, N); // Use RectangleRule !!!
cout << "Approximate finite integral = " << integral << "\n";
}
|