Movatterモバイル変換


[0]ホーム

URL:


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

Commit34a663a

Browse files
vil02appgurueu
andauthored
fix: hadnle zeros at the endpoints inBisectionMethod (#1640)
* fix: hadnle zeros at the endpoints* style: use simpler syntax express polynomialsCo-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com>---------Co-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com>
1 parent702840b commit34a663a

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
consthasRoot=(a,b,func)=>{
26-
returnfunc(a)*func(b)<0
26+
returnfunc(a)*func(b)<=0
2727
}
2828
if(hasRoot(a,b,func)===false){
2929
throwError(
@@ -45,10 +45,9 @@ const findRoot = (a, b, func, numberOfIterations) => {
4545
constprod2=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)returnfindRoot(m,b,func,--numberOfIterations)
49-
elseif(prod1<0&&prod2>0)
50-
returnfindRoot(a,m,func,--numberOfIterations)
51-
elsethrowError('Unexpected behavior')
48+
if(prod2<=0)returnfindRoot(m,b,func,--numberOfIterations)
49+
50+
returnfindRoot(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-
constroot=findRoot(
5-
0,
6-
1.5,
7-
(x)=>{
8-
returnMath.pow(x,2)-3*x+2
9-
},
10-
8
11-
)
4+
constroot=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+
constroot=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)

[8]ページ先頭

©2009-2025 Movatter.jp