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

Function findRoot

Maths/BisectionMethod.js:15–51  ·  view source on GitHub ↗
(a, b, func, numberOfIterations)

Source from the content-addressed store, hash-verified

13 */
14
15const findRoot = (a, b, func, numberOfIterations) => {
16 // Check if a given real value belongs to the function's domain
17 const belongsToDomain = (x, f) => {
18 const res = f(x)
19 return !Number.isNaN(res)
20 }
21 if (!belongsToDomain(a, func) || !belongsToDomain(b, func))
22 throw Error("Given interval is not a valid subset of function's domain")
23
24 // Bolzano theorem
25 const hasRoot = (a, b, func) => {
26 return func(a) * func(b) <= 0
27 }
28 if (hasRoot(a, b, func) === false) {
29 throw Error(
30 'Product f(a)*f(b) has to be negative so that Bolzano theorem is applied'
31 )
32 }
33
34 // Declare m
35 const m = (a + b) / 2
36
37 // Recursion terminal condition
38 if (numberOfIterations === 0) {
39 return m
40 }
41
42 // Find the products of f(m) and f(a), f(b)
43 const fm = func(m)
44 const prod1 = fm * func(a)
45 const prod2 = fm * func(b)
46
47 // Depending on the sign of the products above, decide which position will m fill (a's or b's)
48 if (prod2 <= 0) return findRoot(m, b, func, --numberOfIterations)
49
50 return findRoot(a, m, func, --numberOfIterations)
51}
52
53export { findRoot }

Callers 1

Calls 2

belongsToDomainFunction · 0.85
hasRootFunction · 0.85

Tested by

no test coverage detected