Skip to content

Instantly share code, notes, and snippets.

@grossvogel
Last active May 17, 2019 15:14
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/1b0cdaf753f92149c19a8255b9cfdbdd to your computer and use it in GitHub Desktop.
Save grossvogel/1b0cdaf753f92149c19a8255b9cfdbdd to your computer and use it in GitHub Desktop.
describe('newton\'s method', () => {
it('solves polynomial functions from a guess within 0.5', () => {
const solverTest = (polynomial, x) => {
if (polynomial.degree <= 0) {
return true; // no fun solving constant functions
};
// polynomial(x) = y, so we make a new polynomial
// polynomialWithZero such that polynomialWithZero(x) = 0
const y = polynomial.evaluate(x);
const polynomialWithZero = polynomial.setCoefficient(0, polynomial.coefficients[0] - y);
// use a random guess within 0.5 of the right answer
const delta = jsc.random.number(-0.5, 0.5);
const solution = newton.solve(polynomialWithZero, x + delta);
// because we're doing analytical math with native JavaScript numbers
// we expect floating point error, so we test
// approximate equality w/ a custom function
return approxEqual(polynomial.evaluate(solution), y);
};
const solvesPolynomialFunctions = jsc.forall(
arbitraryPolnomial,
jsc.integer(10),
solverTest
);
// size: 10 limits the _degree_ of the polynomials tested
// this is where we'd provide a larger size for the smap arbitrary
jsc.assert(solvesPolynomialFunctions, { size: 10 });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment