Skip to content

Instantly share code, notes, and snippets.

@grossvogel
Created May 17, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grossvogel/b95a5276defd313a7b3aac9d6ea67992 to your computer and use it in GitHub Desktop.
Save grossvogel/b95a5276defd313a7b3aac9d6ea67992 to your computer and use it in GitHub Desktop.
/**
* Find a zero of the given polynomial near the provided guess
* @param {Polynomial} polynomial
* @param {number} guessX - x value near the zero we're looking for
* @param {number} tolerance - how close we need to be to the desired Y
* @param {number} maxIterations - how many iterations before we fail
*/
const solve = (polynomial, guessX, tolerance = 0.000001, maxIterations = 1000) => {
const derivative = polynomial.derivative;
let iteration = 0;
let x = guessX;
let y = polynomial.evaluate(x);
while(Math.abs(y) > tolerance && iteration < maxIterations) {
x = x - (polynomial.evaluate(x) / derivative.evaluate(x));
y = polynomial.evaluate(x);
iteration++;
}
if (Math.abs(y) <= tolerance) {
return x;
} else {
throw new Error(
`Gave up after ${iteration} iterations. Last approximation: ${x}`
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment