Polynomials

Posted on Jan 07, 2019

A great book to introduce mathematical modeling and machine learning to programmers is A Programmer's Introduction to Mathematics. Of course I'm not just gonna read it but I'm also building some visuals to get a better grasp on the concepts.

The book starts with introducing Polynomials so I've made a javascript implementation of a polynomial generator and created some minimalist charts out of it using the React Vis library that I thought to share here.

The main function is this:

function polynomial(coefficients) {
  return {
    degree: coefficients.length,
    coefficients: coefficients,
    description: function() {
      return this.coefficients.reduce((description, coefficient, n) => {
        if(coefficient === 0) {
          return description
        }
        let next = description + `${coefficient}x^${n}`
        if(n < this.coefficients.length-1) {
          next += " + "
        }
        return next
      }, 'f(x) = ')
    },
    calculate: function(x) {
      return this.coefficients.reduce((value, coefficient, n) => {
        return value + coefficient*Math.pow(x, n)
      }, 0)
    }
  }
}

And I use it like this:

// generate a polynomial with coefficients
// -80, -26, 145, 28, -26, -2, 1
let poly = polynomial([-80, -26, 145, 28, -26, -2, 1])
// calculates the function for x = 3.9
console.log(poly.calculate(3.9))
// returns a string with a mathematical description
console.log(poly.description())

Try to guess what the coefficients are for each visual ;)

Artboard 1@2x.png

poly-plot-1.png

poly-plot-2.png

poly-plot-3.png

poly-plot-4.png

poly-plot-6.png

poly-plot-7.png

poly-plot-9.png

poly-plot-10.png

poly-plot-11.png

poly-plot-12.png

Code can be found here on my github: https://github.com/dp50mm/Polynomial-Generator