simpsons rule in javascript

Simpson's rule is a numerical integration technique that approximates the definite integral of a function by computing a weighted average of the function values at the endpoints and the midpoint of the interval.

Here is an implementation of Simpson's rule in JavaScript:

index.tsx
function simpsonsRule(func, a, b, n) {
    if (n % 2 !== 0) {
        throw "n must be even";
    }
    var h = (b - a) / n;
    var sum = func(a) + func(b);
    for (var i = 1; i < n; i++) {
        var x = a + i * h;
        if (i % 2 === 0) {
            sum += 2 * func(x);
        } else {
            sum += 4 * func(x);
        }
    }
    return (h / 3) * sum;
}
371 chars
17 lines

This function takes four parameters:

  • func: the function to integrate
  • a and b: the endpoints of the interval
  • n: the number of subintervals to use in the approximation

Here's an example of how to use the simpsonsRule function:

index.tsx
var func = function(x) {
    return Math.sin(x);
};
var a = 0;
var b = Math.PI;
var n = 10;
var approx = simpsonsRule(func, a, b, n);
console.log(approx); // outputs 2.000109517174688
184 chars
9 lines

This example integrates the function sin(x) over the interval [0, pi] using 10 subintervals. The computed approximation of the integral is 2.000109517174688.

related categories

gistlibby LogSnag