Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 6x 6x 6x 5x 5x 5x 5x 7x 7x 5x 2x 5x 5x 5x 5x 5x 5x 5x 5x 187x 187x 187x 4x 183x 183x 87x 96x 1x | import { RootFinderOptions, IRootFinder, Root } from '../definition'
import { Polynomial } from '../../polynomial'
import { isValidRoot } from '../../utils'
export class BisectionRootFinder implements IRootFinder {
constructor(protected readonly options: RootFinderOptions) {}
protected findUpperLimit(polynomial: Polynomial): number {
const maxIterations = this.options.maxIterations!
let iteration: number = 0
let result: number = 1
while (iteration++ < maxIterations) {
const calculated = polynomial.calculate(result)
if (calculated < 0) {
return result
}
result *= 2
}
return NaN
}
public findRoot(polynomial: Polynomial): Root {
const upperLimit = this.findUpperLimit(polynomial)
Iif (!isValidRoot(upperLimit)) {
return {
converged: false,
iterations: 0,
value: NaN,
}
}
const limits: [number, number] = [0, upperLimit]
const epsilon = this.options.epsilon!
const maxIterations = this.options.maxIterations!
let iteration: number = 0
let result: number = 0
while (iteration++ < maxIterations) {
const delta = Math.abs(limits[0] - limits[1])
result = (limits[0] + limits[1]) / 2
if (delta < epsilon) {
return {
converged: true,
iterations: iteration,
value: result,
}
}
const calculated = polynomial.calculate(result)
if (calculated < 0) {
limits[1] = result
} else {
limits[0] = result
}
}
return {
converged: false,
iterations: iteration - 1,
value: result,
}
}
}
|