|
| 1 | +/** |
| 2 | + * |
| 3 | + * @file |
| 4 | + * @brief Find real roots of a function in a specified interval [a, b], where f(a)*f(b) < 0 |
| 5 | + * |
| 6 | + * @details Given a function f(x) and an interval [a, b], where f(a) * f(b) < 0, find an approximation of the root |
| 7 | + * by calculating the middle m = (a + b) / 2, checking f(m) * f(a) and f(m) * f(b) and then by choosing the |
| 8 | + * negative product that means Bolzano's theorem is applied,, define the new interval with these points. Repeat until |
| 9 | + * we get the precision we want [Wikipedia](https://en.wikipedia.org/wiki/Bisection_method) |
| 10 | + * |
| 11 | + * @author [ggkogkou](https://github.com/ggkogkou) |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +const 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)) throw Error("Given interval is not a valid subset of function's domain") |
| 22 | + |
| 23 | + // Bolzano theorem |
| 24 | + const hasRoot = (a, b, func) => { |
| 25 | + return func(a) * func(b) < 0 |
| 26 | + } |
| 27 | + if (hasRoot(a, b, func) === false) { throw Error('Product f(a)*f(b) has to be negative so that Bolzano theorem is applied') } |
| 28 | + |
| 29 | + // Declare m |
| 30 | + const m = (a + b) / 2 |
| 31 | + |
| 32 | + // Recursion terminal condition |
| 33 | + if (numberOfIterations === 0) { return m } |
| 34 | + |
| 35 | + // Find the products of f(m) and f(a), f(b) |
| 36 | + const fm = func(m) |
| 37 | + const prod1 = fm * func(a) |
| 38 | + const prod2 = fm * func(b) |
| 39 | + |
| 40 | + // Depending on the sign of the products above, decide which position will m fill (a's or b's) |
| 41 | + if (prod1 > 0 && prod2 < 0) return findRoot(m, b, func, --numberOfIterations) |
| 42 | + else if (prod1 < 0 && prod2 > 0) return findRoot(a, m, func, --numberOfIterations) |
| 43 | + else throw Error('Unexpected behavior') |
| 44 | +} |
| 45 | + |
| 46 | +export { findRoot } |
0 commit comments