Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 34a663a

Browse files
vil02appgurueu
andauthored
fix: hadnle zeros at the endpoints in BisectionMethod (#1640)
* fix: hadnle zeros at the endpoints * style: use simpler syntax express polynomials Co-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com> --------- Co-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com>
1 parent 702840b commit 34a663a

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed

‎Maths/BisectionMethod.js

Lines changed: 4 additions & 5 deletions
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 }

‎Maths/test/BisectionMethod.test.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,7 @@
11
import { findRoot } from '../BisectionMethod'
22

33
test('Equation f(x) = x^2 - 3*x + 2 = 0, has root x = 1 in [a, b] = [0, 1.5]', () => {
4-
const root = findRoot(
5-
0,
6-
1.5,
7-
(x) => {
8-
return Math.pow(x, 2) - 3 * x + 2
9-
},
10-
8
11-
)
4+
const root = findRoot(0, 1.5, (x) => x ** 2 - 3 * x + 2, 8)
125
expect(root).toBe(0.9990234375)
136
})
147

@@ -35,3 +28,12 @@ test('Equation f(x) = sqrt(x) + e^(2*x) - 8*x = 0, has root x = 0.93945851 in [a
3528
)
3629
expect(Number(Number(root).toPrecision(8))).toBe(0.93945851)
3730
})
31+
32+
test('Equation f(x) = x^3 = 0, has root x = 0.0 in [a, b] = [-1.0, 1.0]', () => {
33+
const root = findRoot(-1.0, 1.0, (x) => x ** 3, 32)
34+
expect(root).toBeCloseTo(0.0, 5)
35+
})
36+
37+
test('Throws an error when function does not change sign', () => {
38+
expect(() => findRoot(-1.0, 1.0, (x) => x ** 2, 10)).toThrowError()
39+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /