|
|
|
|
|
Aproximation = sum of the area of the rectangles = area of rectangle 1 + area of rectangle 2 + ... + area of rectangle n = width × f( a + (1-1)×width ) + width × f( a + (2-1)×width ) + ... + width × f( a + (n-1)×width ) |
|
Example: compute 12 + 22 + 32 + ... + i2 + ... + n2
|
Aproximation = sum of the area of the rectangles = width × f( a + (1-1)×width ) + width × f( a + (2-1)×width ) + ... + width × f( a + (i-1)×width ) + ... + width × f( a + (n-1)×width ) Where: width = (b - a) / n |
ith term = width × f( a + (i-1)×width ) |
Variables: double w; // w contains the width double sum; // sum contains the running sum Algorithm to compute the sum: w = (b - a)/n; // Compute width sum = 0.0; // Clear running sum for ( i = 1; i <= n; i++ ) { sum = sum + w*f( a + (i-1)*w ); } |
input a, b, n; // a = left end point of integral // b = right end point of integral // n = # rectangles used in the approximation |
public class RectangleMethod01 { public static void main(String[] args) { double a, b, w, sum, x_i; int i, n; **** Initialize a, b, n **** /* --------------------------------------------------- The Rectangle Rule Algorithm --------------------------------------------------- */ w = (b-a)/n; // Compute width sum = 0.0; // Clear running sum for ( i = 1; i <= n; i++ ) { x_i = a + (i-1)*w; // Use x_i to simplify formula... sum = sum + ( w * f(x_i) ); // width * height of rectangle i } System.out.println("Approximate integral value = " + sum); } } |
public class RectangleMethod01 { public static void main(String[] args) { double a, b, w, sum, x_i; int i, n; a = 0.0; b = 1.0; // 1∫2x3 dx n = 1000; // Use larger value for better approximation /* --------------------------------------------------- The Rectangle Rule Algorithm --------------------------------------------------- */ w = (b-a)/n; // Compute width sum = 0.0; // Clear running sum for ( i = 1; i <= n; i++ ) { x_i = a + (i-1)*w; sum = sum + ( w * (x_i * x_i * x_i) ); // f(x_i) = (x_i)3 } System.out.println("Approximate integral value = " + sum); } } |
How to run the program:
|
public class RectangleMethod02 { public static void main(String[] args) { double a, b, w, sum, x_i; int i, n; a = 1.0; b = 2.0; // 1∫2(1/x) dx n = 1000; // Use larger value for better approximation /* --------------------------------------------------- The Rectangle Rule Algorithm --------------------------------------------------- */ w = (b-a)/n; // Compute width sum = 0.0; // Clear running sum for ( i = 1; i <= n; i++ ) { x_i = a + (i-1)*w; sum = sum + ( w * (1/x_i) ); // f(x_i) = 1/x_i } System.out.println("Approximate integral value = " + sum); } } |
How to run the program:
|
Clearly:
|
However:
|
|
You can experience the trade off phenomenon by using n = 1000000 in the above algorithm.
It will run slower, but give you very accurate results !
Outputs for n = 1000000:
|