MCPcopy Index your code
hub / github.com/TheAlgorithms/JavaScript / integralEvaluation

Function integralEvaluation

Maths/MidpointIntegration.js:20–61  ·  view source on GitHub ↗

* * @title Midpoint rule for definite integral evaluation * @author [ggkogkou](https://github.com/ggkogkou) * @brief Calculate definite integrals with midpoint method * * @details The idea is to split the interval in a number N of intervals and use as interpolation points the xi * for which it

(N, a, b, func)

Source from the content-addressed store, hash-verified

18 */
19
20function 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)) {
23 throw new TypeError('Expected integer N and finite a, b')
24 }
25 if (N <= 0) {
26 throw Error('N has to be >= 2')
27 } // check if N > 0
28 if (a > b) {
29 throw Error('a must be less or equal than b')
30 } // Check if a < b
31 if (a === b) return 0 // If a === b integral is zero
32
33 // Calculate the step h
34 const h = (b - a) / N
35
36 // Find interpolation points
37 let xi = a // initialize xi = x0
38 const pointsArray = []
39
40 // Find the sum {f(x0+h/2) + f(x1+h/2) + ... + f(xN-1+h/2)}
41 let temp
42 for (let i = 0; i < N; i++) {
43 temp = func(xi + h / 2)
44 pointsArray.push(temp)
45 xi += h
46 }
47
48 // Calculate the integral
49 let result = h
50 temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
51
52 result *= temp
53
54 if (Number.isNaN(result)) {
55 throw Error(
56 'Result is NaN. The input interval does not belong to the functions domain'
57 )
58 }
59
60 return result
61}
62
63export { integralEvaluation }

Callers 1

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected