forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBisectionMethod.js
More file actions
Latest commit
54 lines (47 loc) · 1.74 KB
/
Copy pathBisectionMethod.js
File metadata and controls
54 lines (47 loc) · 1.74 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
/**
*
* @file
* @brief Find real roots of a function in a specified interval [a, b], where f(a)*f(b) < 0
*
* @details Given a function f(x) and an interval [a, b], where f(a) * f(b) < 0, find an approximation of the root
* by calculating the middle m = (a + b) / 2, checking f(m) * f(a) and f(m) * f(b) and then by choosing the
* negative product that means Bolzano's theorem is applied,, define the new interval with these points. Repeat until
* we get the precision we want [Wikipedia](https://en.wikipedia.org/wiki/Bisection_method)
*
* @author [ggkogkou](https://github.com/ggkogkou)
*
*/
constfindRoot=(a,b,func,numberOfIterations)=>{
// Check if a given real value belongs to the function's domain
constbelongsToDomain=(x,f)=>{
constres=f(x)
return!Number.isNaN(res)
}
if(!belongsToDomain(a,func)||!belongsToDomain(b,func))
throwError("Given interval is not a valid subset of function's domain")
// Bolzano theorem
consthasRoot=(a,b,func)=>{
returnfunc(a)*func(b)<0
}
if(hasRoot(a,b,func)===false){
throwError(
'Product f(a)*f(b) has to be negative so that Bolzano theorem is applied'
)
}
// Declare m
constm=(a+b)/2
// Recursion terminal condition
if(numberOfIterations===0){
returnm
}
// Find the products of f(m) and f(a), f(b)
constfm=func(m)
constprod1=fm*func(a)
constprod2=fm*func(b)
// Depending on the sign of the products above, decide which position will m fill (a's or b's)
if(prod1>0&&prod2<0)returnfindRoot(m,b,func,--numberOfIterations)
elseif(prod1<0&&prod2>0)
returnfindRoot(a,m,func,--numberOfIterations)
elsethrowError('Unexpected behavior')
}
export{findRoot}