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

Function integralEvaluation

Maths/SimpsonIntegration.js:24–76  ·  view source on GitHub ↗
(N, a, b, func)

Source from the content-addressed store, hash-verified

22 */
23
24function integralEvaluation(N, a, b, func) {
25 // Check if N is an even integer
26 let isNEven = true
27 if (N % 2 !== 0) isNEven = false
28
29 if (!Number.isInteger(N) || Number.isNaN(a) || Number.isNaN(b)) {
30 throw new TypeError('Expected integer N and finite a, b')
31 }
32 if (!isNEven) {
33 throw Error('N is not an even number')
34 }
35 if (N <= 0) {
36 throw Error('N has to be >= 2')
37 }
38
39 // Check if a < b
40 if (a > b) {
41 throw Error('a must be less or equal than b')
42 }
43 if (a === b) return 0
44
45 // Calculate the step h
46 const h = (b - a) / N
47
48 // Find interpolation points
49 let xi = a // initialize xi = x0
50 const pointsArray = []
51
52 // Find the sum {f(x0) + 4*f(x1) + 2*f(x2) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)}
53 let temp
54 for (let i = 0; i < N + 1; i++) {
55 if (i === 0 || i === N) temp = func(xi)
56 else if (i % 2 === 0) temp = 2 * func(xi)
57 else temp = 4 * func(xi)
58
59 pointsArray.push(temp)
60 xi += h
61 }
62
63 // Calculate the integral
64 let result = h / 3
65 temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
66
67 result *= temp
68
69 if (Number.isNaN(result)) {
70 throw Error(
71 "Result is NaN. The input interval doesn't belong to the functions domain"
72 )
73 }
74
75 return result
76}
77
78export { integralEvaluation }

Callers 1

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected