Re: numerical analysis (composite numerical integration)
- From: "user923005" <dcorbit@xxxxxxxxx>
- Date: 3 Jan 2007 17:48:30 -0800
Carl Barron wrote:
In article <1167818925.307715.102700@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
user923005 <dcorbit@xxxxxxxxx> wrote:
I am horrified at my old trapezoidal rule. It had redundantI don't see redundant evaluations of f(x). I do see some
calculations of f(). This is how it should have been done:
double trapezoidal_rule(double a, double b, int n, double (*f)(double))
{
double area = 0;
double h = (b - a) / n;
unsigned i;
area = f(a);
for (i = 1; i < n; i++) {
area += f(a + i * h) * 2.0;
}
area += f(b);
area *= h * 0.5;
return area;
}
reductions using distributive laws and removing unneeded multiplies
by computing the internal sum, and the sum of end values separately
then area = h*(sum(f(a+i*h),i=1..n-1)+1/2(f(a)+f(b)))
in C this is something like:
area = 0.5*(f(a)+f(b));
a += h;
for(i = 1 ;i < n-1 ;++i,a+=h) area += f(a);
return h*area;
this involves 2 mulitplies instead of (n-1)+2 [=n+1] multiplies.
This is the original -- it has exactly 2*n function calls:
double trapezoidal_rule(double a, double b, int n, double (*f)
(double))
{
double area = 0;
double h = (b - a) / n;
unsigned i;
for (i = 1; i <= n; i++) {
area += 0.5 * h * (f(a + (i - 1) * h) + f(a + i * h));
}
return area;
}
This is the modified version -- it has exactly n+1 function calls:
double trapezoidal_rule(double a, double b, int n, double (*f)(double))
{
double h = (b - a) / n;
double area = f(a);
unsigned i;
for (i = 1; i < n; i++) {
area += f(a + i * h) * 2.0;
}
return (area + f(b)) * h * 0.5;
}
You probably saw my intermediate version which removed the redundant
function calls but still needed a little bit of tidying up:
double trapezoidal_rule(double a, double b, int n, double (*f)(double))
{
double area = 0; /* useless assignment corrected above. */
double h = (b - a) / n;
unsigned i;
area = f(a);
for (i = 1; i < n; i++) {
area += f(a + i * h) * 2.0;
}
area += f(b);
area *= h * 0.5; /* direct return up above is better. */
return area;
}
.
- Follow-Ups:
- Re: numerical analysis (composite numerical integration)
- From: user923005
- Re: numerical analysis (composite numerical integration)
- References:
- Re: numerical analysis (composite numerical integration)
- From: user923005
- Re: numerical analysis (composite numerical integration)
- From: Carl Barron
- Re: numerical analysis (composite numerical integration)
- Prev by Date: Re: numerical analysis (composite numerical integration)
- Next by Date: Re: Getting the position of orthogonal columns using SVD
- Previous by thread: Re: numerical analysis (composite numerical integration)
- Next by thread: Re: numerical analysis (composite numerical integration)
- Index(es):
Relevant Pages
|