newton.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/seven/newton.js
 
import {Complex} from "./complex.js"
import {F, FPrime} from "./function.js"

const CONVERGE = 0.001
const COLOR_SCALE = 2
const DIVERGE = 256*COLOR_SCALE

function Newton(z) {

   let count = 0
   let FofZ = F(z)
   while (FofZ.Mag() > CONVERGE && count < DIVERGE) {
      let num = F(z)
      let denom = FPrime(z)

      if (denom.Real() == 0 && denom.Imag() == 0) {
         denom = new Complex(1,0)
      }

      let fract = num.Div(denom)

      z = z.Sub(fract)
      FofZ = F(z)
      ++count
   }

   return {iterations:count, root:z}
}

let roots = []

export function ResetRoots() {
   roots = []
}

function WhichRoot(answer) {

   let rootFound = answer.root
   let iterations = answer.iterations

   if(iterations >= DIVERGE) {
      return 0
   }

   if (roots.length == 0) {
      roots.push(rootFound)
      return 1
   }

   let close = rootFound.Sub(roots[0]).Mag()
   let closeNo = 0

   for(let i = 1; i < roots.length; ++i) {
      let newClose = rootFound.Sub(roots[i]).Mag()
      if (newClose < close) {
          closeNo = i
          close = newClose
      }
   }

   if(close <= CONVERGE) {
      return closeNo+1
   } else {
      roots.push(rootFound)
      return roots.length
   }
}

export function FindRoot(x,y) {
    let z = new Complex(x,y);
    let answer = Newton(z);

    let root = WhichRoot(answer);

    return {root:root, iterations: answer.iterations}
}