take the integral of a function in typescript

To take the integral of a function in TypeScript, you will need to use numerical integration techniques. There are various numerical integration algorithms, but one of the most commonly used is the Simpson's Rule.

Here is an example TypeScript function that implements Simpson's Rule to find the definite integral of a given function f(x) over the range a to b, using a specified number of intervals n:

index.ts
function simpsonsRuleIntegration(f: (x: number) => number, a: number, b: number, n: number): number {
    const h = (b - a) / n; // Interval width
    let sum = f(a) + f(b); // Initialize sum with first and last terms

    // Loop through intermediate terms
    for (let i = 1; i < n; i++) {
        const x = a + i * h; // Current x value
        sum += 2 * (1 + i % 2) * f(x); // Add current term to sum
    }

    return sum * h / 3; // Return final approximation
}
469 chars
13 lines

To use this function, you would simply pass in your desired function f(x), the range of integration a to b, and the number of intervals n that you want to use. For example, to find the definite integral of the function f(x) = x^2 + 2x - 1 over the range a=0 to b=5, using 100 intervals:

index.ts
const f = (x: number) => x**2 + 2*x - 1;
const integral = simpsonsRuleIntegration(f, 0, 5, 100);
console.log(integral); // Output: 89.08333333333331
149 chars
4 lines

Note that the approximation becomes more accurate as the number of intervals n increases, but at the cost of increased computational complexity. You may need to experiment with different values of n to find the right balance between accuracy and speed for your particular use case.

gistlibby LogSnag