|
| 1 | +/* |
| 2 | +* |
| 3 | +* @file |
| 4 | +* @title Composite Simpson's rule for definite integral evaluation |
| 5 | +* @author: [ggkogkou](https://github.com/ggkogkou) |
| 6 | +* @brief Calculate definite integrals using composite Simpson's numerical method |
| 7 | +* |
| 8 | +* @details The idea is to split the interval in an EVEN number N of intervals and use as interpolation points the xi |
| 9 | +* 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 |
| 10 | +* first and last points of the interval of the integration [a, b]. |
| 11 | +* |
| 12 | +* We create a table of the xi and their corresponding f(xi) values and we evaluate the integral by the formula: |
| 13 | +* I = h/3 * {f(x0) + 4*f(x1) + 2*f(x2) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)} |
| 14 | +* |
| 15 | +* That means that the first and last indexed i f(xi) are multiplied by 1, |
| 16 | +* the odd indexed f(xi) by 4 and the even by 2. |
| 17 | +* |
| 18 | +* N must be even number and a<b. By increasing N, we also increase precision |
| 19 | +* |
| 20 | +* More info: [Wikipedia link](https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule) |
| 21 | +* |
| 22 | +*/ |
| 23 | + |
| 24 | + |
| 25 | +function integralEvaluation(N, a, b, func) { |
| 26 | + // Check if N is an even integer |
| 27 | + let isNEven = (N) => { |
| 28 | + if(N%2 === 0) |
| 29 | + return true; |
| 30 | + return false; |
| 31 | + } |
| 32 | + if(!Number.isInteger(N) || Number.isNaN(a) || Number.isNaN(b)) { throw new TypeError("Expected integer N and finite a, b"); } |
| 33 | + if(!isNEven) { throw "N is not an even number"; } |
| 34 | + |
| 35 | + // Check if a < b |
| 36 | + if(a > b) { throw "a must be less or equal than b"; } |
| 37 | + if(a === b) return 0; |
| 38 | + |
| 39 | + // Calculate the step h |
| 40 | + const h = (b - a) / N; |
| 41 | + |
| 42 | + // Find interpolation points |
| 43 | + let xi = a; // initialize xi = x0 |
| 44 | + let pointsArray = []; |
| 45 | + |
| 46 | + // Find the sum {f(x0) + 4*f(x1) + 2*f(x2) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)} |
| 47 | + let temp; |
| 48 | + for(let i = 0; i < N+1; i++){ |
| 49 | + if(i === 0 || i === N) temp = func(xi); |
| 50 | + else if(i%2 === 0) temp = 2*func(xi); |
| 51 | + else temp = 4*func(xi); |
| 52 | + |
| 53 | + pointsArray.push(temp); |
| 54 | + xi += h; |
| 55 | + } |
| 56 | + |
| 57 | + // Calculate the integral |
| 58 | + let result = h/3; |
| 59 | + temp = 0; |
| 60 | + for(let i=0; i < pointsArray.length; i++) temp += pointsArray[i]; |
| 61 | + |
| 62 | + result *= temp; |
| 63 | + |
| 64 | + if (Number.isNaN(result)) { throw "Result is NaN. The input interval doesn't belong to the function's domain"; } |
| 65 | + |
| 66 | + return result; |
| 67 | +} |
| 68 | + |
| 69 | +export { integralEvaluation } |
0 commit comments