Numerical Integration

This notebook gives a numerical approximation to the definite integral (∫_a^b)f(x)dx.  (I used the writing assistant, available in the Palettes menu.)

numInt[function_, n_, a_, b_, method_] := Module[{i,h, sum, out},
(* gives an approximation of (∫_a^b)function[x]\[DifferentialD]x using various methods *)

If[method == "LHS", (* Left Hand Sum *)
sum = 0;
h = (b-a)/n;
For[i = 0, i < n, i++,
xi = a + i*h;
sum = sum + function[xi];
];
out = h*sum
];

If[method == "RHS", (* Right Hand Sum *)
sum = 0;
h = (b-a)/n;
For[i = 1, i ≤  n, i++,
xi = a + i*h;
sum = sum + function[xi];
];
out = h*sum
];

out  (* The last line of the Module is the output *)
]

Now test the code.

f[x_] := x^2

numInt[f, 10, 0, 1, "LHS"]

You can do the same calculation using a “pure function”.  The variable is a “#” and you put “&” at the end.

numInt[#^2&, 10, 0, 1, "LHS"]