Created
May 17, 2019 14:45
-
-
Save grossvogel/b95a5276defd313a7b3aac9d6ea67992 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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