forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpsonIntegration.js
More file actions
Latest commit
78 lines (66 loc) · 2.25 KB
/
Copy pathSimpsonIntegration.js
File metadata and controls
78 lines (66 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
*
* @file
* @title Composite Simpson's rule for definite integral evaluation
* @author: [ggkogkou](https://github.com/ggkogkou)
* @brief Calculate definite integrals using composite Simpson's numerical method
*
* @details The idea is to split the interval in an EVEN number N of intervals and use as interpolation points the xi
* 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
* first and last points of the interval of the integration [a, b].
*
* We create a table of the xi and their corresponding f(xi) values and we evaluate the integral by the formula:
* I = h/3 * {f(x0) + 4*f(x1) + 2*f(x2) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)}
*
* That means that the first and last indexed i f(xi) are multiplied by 1,
* the odd indexed f(xi) by 4 and the even by 2.
*
* N must be even number and a<b. By increasing N, we also increase precision
*
* More info: [Wikipedia link](https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule)
*
*/
functionintegralEvaluation(N,a,b,func){
// Check if N is an even integer
letisNEven=true
if(N%2!==0)isNEven=false
if(!Number.isInteger(N)||Number.isNaN(a)||Number.isNaN(b)){
thrownewTypeError('Expected integer N and finite a, b')
}
if(!isNEven){
throwError('N is not an even number')
}
if(N<=0){
throwError('N has to be >= 2')
}
// Check if a < b
if(a>b){
throwError('a must be less or equal than b')
}
if(a===b)return0
// Calculate the step h
consth=(b-a)/N
// Find interpolation points
letxi=a// initialize xi = x0
constpointsArray=[]
// Find the sum {f(x0) + 4*f(x1) + 2*f(x2) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)}
lettemp
for(leti=0;i<N+1;i++){
if(i===0||i===N)temp=func(xi)
elseif(i%2===0)temp=2*func(xi)
elsetemp=4*func(xi)
pointsArray.push(temp)
xi+=h
}
// Calculate the integral
letresult=h/3
temp=pointsArray.reduce((acc,currValue)=>acc+currValue,0)
result*=temp
if(Number.isNaN(result)){
throwError(
"Result is NaN. The input interval doesn't belong to the functions domain"
)
}
returnresult
}
export{integralEvaluation}