newton.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/start_class/newton.js
 
import {ComplexT} 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 ComplexT(1,1)
        }

        let fract = num.Div(denom)
        z = z.Sub(fract)
        FofZ = F(z)
        ++count

    }
    //return [z, count]
    return {iterations: count, root:z}
}

let roots = []

export function ResetRoots() {
    roots = []
}

function WhichRoot(answer) {
    let root = answer.root
    let iterations = answer.iterations

    if (iterations >= DIVERGE) {
       return 0
    }

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

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

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

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

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

    let root = WhichRoot(answer);

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