Plotting the characteristic polynomial of a matrix
Next step is determining the roots of the characteristic polynomial of a matrix. Before working on extracting the roots using Newton’s method I wanted to be able to visualize the function.
First we need to, given a square matrix as an input, return the characteristic polynomial, which basically is a function taking x as an argument and returning the determinant of the input matrix where x is subtracted for every element on the diagonal:
function pol(m) { var size = Math.sqrt(m.length); if (size % 1 !== 0) { return null; } return function(x) { return det(m.map( function(val, i) { return val - ( Math.floor(i / size) === i % size ? x : 0); } )); } }
Then we need to plot it, here’s the function:
function plot(pol, cont, range = 10, size = 500) { var step = ( range * 2 ) / size; var points = []; for(var x = 0; x < size; x ++) { points.push(x, ',', pol(x * step - range) + size / 2); } cont.innerHTML = '<svg viewBox="0 0 ' + size + ' ' + size + '">' + '<line stroke="#ddd" stroke-width="1"' + 'x1="0" y1="'+ size / 2 +'" ' + 'x2="'+ size +'" y2="'+ size / 2 + '"/>' + '<line stroke="#ddd" stroke-width="1"' + 'x1="'+ size / 2 +'" y1="0" ' + 'x2="'+ size / 2 + '" y2="'+ size +'"/>' + '<polyline fill="none" stroke="#0074d9" stroke-width="2"' + 'points="' + points.join(' ') + '"/>"' + '</svg>'; }
Now we can try to invoke it with:
var matrix = [ 1, 2, 6, 1, 3, 4, 0, 4, 5 ]; plot(pol(matrix), document.querySelector('div'));
And here's the resulting SVG chart:
As usual here's the JSFiddle to play with.
Thanks!