All files / src/root-finder/newton newton.ts

100% Statements 27/27
100% Branches 6/6
100% Functions 4/4
100% Lines 27/27

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    6x   6x 8x     6x 6x   6x 6x   6x 138x 12x   126x       6x       7x 7x 7x   7x   7x   7x 28x 28x 28x   28x   28x 5x             23x 1x               1x              
import { RootFinderOptions, IRootFinder, Root } from '../definition'
import { Polynomial } from '../../polynomial'
import { isValidRoot } from '../../utils'
 
export class NewtonRootFinder implements IRootFinder {
  constructor(protected readonly options: RootFinderOptions) {}
 
  protected autoEstimate(polynomial: Polynomial): number {
    const coefficients = polynomial.getCoefficients()
    const { length } = coefficients
 
    let positive: number = 0
    let negative: number = 0
 
    coefficients.forEach(coefficient => {
      if (coefficient > 0) {
        positive += coefficient
      } else {
        negative -= coefficient
      }
    })
 
    return (positive / negative - 1) / length + 1
  }
 
  public findRoot(polynomial: Polynomial): Root {
    const epsilon = this.options.epsilon!
    const { estimate } = this.options
    const maxIterations = this.options.maxIterations!
 
    let iteration: number = 0
    let root: number =
      estimate === 'auto' ? this.autoEstimate(polynomial) : estimate!
 
    while (iteration++ < maxIterations) {
      const tangent = polynomial.getTangentAt(root)
      const newRoot = tangent.findRoot().value
      const delta = Math.abs(newRoot - root)
 
      root = newRoot
 
      if (delta < epsilon) {
        return {
          converged: true,
          iterations: iteration,
          value: root,
        }
      }
 
      if (!isValidRoot(root)) {
        return {
          converged: false,
          iterations: iteration,
          value: root,
        }
      }
    }
 
    return {
      converged: false,
      iterations: iteration - 1,
      value: root,
    }
  }
}