JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

JavaScript

const add = (...nums) => nums.reduce((num, sum) => [num[0] + sum[0], num[1] + sum[1]], [0, 0]);
const mult = (a, b) => [a[0] * b[0] - a[1] * b[1], a[1] * b[0] + a[0] * b[1]];
const pow = (a, power) => {
	let result = [1, 0];
  for (let i = 0; i < power; i++) {
    result = mult(result, a);
  }
  return result;
}

function findRoots(f, numberToFind) {
	let knownRoots = [];
  
  const func = (x) => {
  	let value = f(x);
    for (const root of knownRoots) {
    	value /= (x - root);
    }
    return value;
  }
  
  for (let i = 0; i < numberToFind; i++) {
  	knownRoots.push(findRoot(func));
  }
  
  return knownRoots;
}

function findRoot(f) {
	let guess = 0;
  const dx = 0.001;
  
  for (let i = 0; i < 100; i++) {
  	const fPrime = (f(guess + dx / 2) - f(guess - dx / 2)) / dx;
    guess += -f(guess) / fPrime;
  }
  
  return guess;
}

const f = (x) => {
	// return x**5 - 15 * x**4 + 85 * x**3 - 225 * x**2 + 274 * x - 120;
  return add(
  	pow(x, 5),
    mult([], pow(x, 4)),
    mult([], pow(x, 3)),
    mult([], pow(x, 2)),
    mult([], pow(x, 1)),
    []
  );
}

console.log(findRoots(f, 5));