simpsons 1/3 rulee in javascript

The Simpson's 1/3 rule is a numerical method for approximating definite integrals. Here's how you can implement it in JavaScript:

index.tsx
function simpsons_1_3_rule(f, a, b, n=2) {
    /* f: function to be integrated
       a: lower limit of integration
       b: upper limit of integration
       n: number of intervals (must be even)
    */
    if (n % 2 == 1) {
        throw new Error('Number of intervals must be even');
    }

    let h = (b - a) / n;

    let sum_odd = 0;
    for (let i = 1; i < n; i += 2) {
        sum_odd += f(a + i * h);
    }

    let sum_even = 0;
    for (let i = 2; i < n-1; i += 2) {
        sum_even += f(a + i * h);
    }

    let integral = (b - a) / (3*n) * (f(a) + 4*sum_odd + 2*sum_even + f(b));
    return integral;
}
621 chars
26 lines

Here, f is the function to be integrated, a and b are the lower and upper limits of integration, respectively, and n is the number of intervals. The function returns the approximate value of the integral.

Note that the number of intervals must be even. If it is odd, an exception is thrown. This is because Simpson's rule requires an even number of intervals to work properly.

Here's an example of using the function to approximate the integral of x^2 over the interval [0, 1]:

index.tsx
function f(x) { return x**2; }
let a = 0;
let b = 1;
let n = 4;

let integral = simpsons_1_3_rule(f, a, b, n);
console.log(integral);  // Output: 0.3333333333333333
165 chars
8 lines

In this example, n=4 is chosen to give a reasonably accurate result. As n is increased, the approximation should become more accurate.

gistlibby LogSnag