|
| 1 | +/** |
| 2 | +* |
| 3 | +* @title Midpoint rule for definite integral evaluation |
| 4 | +* @author [ggkogkou](https://github.com/ggkogkou) |
| 5 | +* @brief Calculate definite integrals with midpoint method |
| 6 | +* |
| 7 | +* @details The idea is to split the interval in a number N of intervals and use as interpolation points the xi |
| 8 | +* for which it applies that xi = x0 + i*h, where h is a step defined as h = (b-a)/N where a and b are the |
| 9 | +* first and last points of the interval of the integration [a, b]. |
| 10 | +* |
| 11 | +* We create a table of the xi and their corresponding f(xi) values and we evaluate the integral by the formula: |
| 12 | +* I = h * {f(x0+h/2) + f(x1+h/2) + ... + f(xN-1+h/2)} |
| 13 | +* |
| 14 | +* N must be > 0 and a<b. By increasing N, we also increase precision |
| 15 | +* |
| 16 | +* [More info link](https://tutorial.math.lamar.edu/classes/calcii/approximatingdefintegrals.aspx) |
| 17 | +* |
| 18 | +*/ |
| 19 | + |
| 20 | +function integralEvaluation (N, a, b, func) { |
| 21 | + // Check if all restrictions are satisfied for the given N, a, b |
| 22 | + if (!Number.isInteger(N) || Number.isNaN(a) || Number.isNaN(b)) { throw new TypeError('Expected integer N and finite a, b') } |
| 23 | + if (N <= 0) { throw Error('N has to be >= 2') } // check if N > 0 |
| 24 | + if (a > b) { throw Error('a must be less or equal than b') } // Check if a < b |
| 25 | + if (a === b) return 0 // If a === b integral is zero |
| 26 | + |
| 27 | + // Calculate the step h |
| 28 | + const h = (b - a) / N |
| 29 | + |
| 30 | + // Find interpolation points |
| 31 | + let xi = a // initialize xi = x0 |
| 32 | + const pointsArray = [] |
| 33 | + |
| 34 | + // Find the sum {f(x0+h/2) + f(x1+h/2) + ... + f(xN-1+h/2)} |
| 35 | + let temp |
| 36 | + for (let i = 0; i < N; i++) { |
| 37 | + temp = func(xi + h / 2) |
| 38 | + pointsArray.push(temp) |
| 39 | + xi += h |
| 40 | + } |
| 41 | + |
| 42 | + // Calculate the integral |
| 43 | + let result = h |
| 44 | + temp = 0 |
| 45 | + for (let i = 0; i < pointsArray.length; i++) temp += pointsArray[i] |
| 46 | + |
| 47 | + result *= temp |
| 48 | + |
| 49 | + if (Number.isNaN(result)) { throw Error('Result is NaN. The input interval does not belong to the functions domain') } |
| 50 | + |
| 51 | + return result |
| 52 | +} |
| 53 | + |
| 54 | +export { integralEvaluation } |
0 commit comments