Skip to content

Instantly share code, notes, and snippets.

View grossvogel's full-sized avatar
🐢

Jason Pollentier grossvogel

🐢
  • Revelry Labs
  • New Orleans, LA
View GitHub Profile
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 boundedInt = jsc.integer(-MAX_COEFFICIENT, MAX_COEFFICIENT);
const polynomialArbitrary = jsc.nearray(boundedInt).smap(
Polynomial.create,
Polynomial.getCoefficents
);
... snip: a bunch of passing inputs
[ 13, 10, 38, 33, 19 ]
[ 10, 38, 33, 19 ]
[ 6, 10, 38, 33, 19 ]
[ 9, 10, 38, 33, 19 ]
[ 10, 10, 38, 33, 19 ]
[ 10, 38, 33, 19 ]
[ 5, 10, 38, 33, 19 ]
[ 7, 10, 38, 33, 19 ]
[ 8, 10, 38, 33, 19 ]
const shrink = polynomial => {
const arrayShrinker = jsc.shrink.array;
const arrayIntShrinker = arrayShrinker(jsc.integer.shrink);
const coefficientSets = arrayIntShrinker(polynomial.coefficients);
return coefficientSets.map(Polynomial.create);
};
/**
* Size in the case of polynomials will be the length of the coefficients array,
* which is one more than the degree of the polynomial
* For simplicity, use integer coefficients
* @param {Integer} size
*/
const generator = size => {
const coefficients = [];
for (i = 0; i < size; i++) {
coefficients.push(jsc.random(-MAX_COEFFICIENT, MAX_COEFFICIENT));
/**
* 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;
class Polynomial {
//...
get derivative() {
const newCoefficients = this.coefficients
.map((coefficient, degree) => coefficient * degree)
.slice(1);
return new Polynomial(newCoefficients);
}
//...
}
const polynomial = new Polynomial([1,2,3]); // 3x^2 + 2x + 1
const y1 = polynomial.evaluate(1); // 6
class Polynomial {
/**
* @param {array} coefficients
* with coefficients[i] being the coefficient for X^i
*/
constructor(coefficients) {
// remove leading 0s, so 0x^2 + 2x + 1 becomes 2x + 1
this._coefficients = this._trimCoefficients(coefficients);
}
const jsc = require('jsverify');
describe('addition', () => {
it('is commutative'() => {
const commutativeTest = (a, b) => add(a, b) === add(b, a);
const commutativeProperty = jsc.forall(jsc.number, jsc.number, commutativeTest);
jsc.assert(commutativeProperty);
});
});