JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
const add = (a, b) => [a[0] + b[0], a[1] + b[1]];
const mult = (a, b) => [a[0] * b[0] - a[1] * b[1], a[1] * b[0] + a[0] * b[1]];
const exp = (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;
}
console.log(findRoots(f, 5));