Skip to content

Commit f2f10bd

Browse files
committed
fix: hadnle zeros at the endpoints
1 parent bd34e9f commit f2f10bd

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

Diff for: Maths/BisectionMethod.js

+4-5
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const findRoot = (a, b, func, numberOfIterations) => {
2323

2424
// Bolzano theorem
2525
const hasRoot = (a, b, func) => {
26-
return func(a) * func(b) < 0
26+
return func(a) * func(b) <= 0
2727
}
2828
if (hasRoot(a, b, func) === false) {
2929
throw Error(
@@ -45,10 +45,9 @@ const findRoot = (a, b, func, numberOfIterations) => {
4545
const prod2 = fm * func(b)
4646

4747
// Depending on the sign of the products above, decide which position will m fill (a's or b's)
48-
if (prod1 > 0 && prod2 < 0) return findRoot(m, b, func, --numberOfIterations)
49-
else if (prod1 < 0 && prod2 > 0)
50-
return findRoot(a, m, func, --numberOfIterations)
51-
else throw Error('Unexpected behavior')
48+
if (prod2 <= 0) return findRoot(m, b, func, --numberOfIterations)
49+
50+
return findRoot(a, m, func, --numberOfIterations)
5251
}
5352

5453
export { findRoot }

Diff for: Maths/test/BisectionMethod.test.js

+25
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,28 @@ test('Equation f(x) = sqrt(x) + e^(2*x) - 8*x = 0, has root x = 0.93945851 in [a
3535
)
3636
expect(Number(Number(root).toPrecision(8))).toBe(0.93945851)
3737
})
38+
39+
test('Equation f(x) = x^3 = 0, has root x = 0.0 in [a, b] = [-1.0, 1.0]', () => {
40+
const root = findRoot(
41+
-1.0,
42+
1.0,
43+
(x) => {
44+
return Math.pow(x, 3)
45+
},
46+
32
47+
)
48+
expect(root).toBeCloseTo(0.0, 5)
49+
})
50+
51+
test('Throws an error when function does not change sign', () => {
52+
expect(() =>
53+
findRoot(
54+
-1.0,
55+
1.0,
56+
(x) => {
57+
return Math.pow(x, 2)
58+
},
59+
10
60+
)
61+
).toThrowError()
62+
})

0 commit comments

Comments
 (0)