xxxxxxxxxx
119
// a game about finding roots of a complex polynomial
// visualzation like: https://math.stackexchange.com/questions/607436/what-do-polynomials-look-like-in-the-complex-plane
// "steam plots"
// using https://github.com/rawify/Complex.js
let poly;
let scaleSlider,zoomSlider;
let attempt;
function setup() {
let c = createCanvas(600,600);
c.mouseClicked(_clicked);
poly = select("#poly");
scaleSlider = select("#scaleSlider");
zoomSlider = select("#zoomSlider");
zoomSlider.input(_changed);
attempt = null;
}
const K = 20;
function draw() {
background("white");
//clip(mask);
let scaling = map(scaleSlider.value(),1,100,.0005,.5);
let zoom = map(zoomSlider.value(),1,100,1.0,100.);
noFill();
for (let j=0;j<height;j+=K){
for (let i=0;i<width;i+=K){
let x,y;
x = map(i,0,width,-zoom,zoom);
y = map(j,0,height,-zoom,zoom);
let [zRe,zIm] = f(poly,x,y,scaling/zoom*4);
stroke("darkgray");
line(i,j,i+zRe,j+zIm);
stroke("gray");
circle(i+zRe,j+zIm,2);
}
}
noStroke();
i = map(0,-zoom,zoom,0,width);
j = map(0,-zoom,zoom,0,height);
fill("darkgreen")
text('0',i-5,j-5);
circle(i,j,5);
i = map(10,-zoom,zoom,0,width);
j = map(0,-zoom,zoom,0,height);
fill("green")
text('10',i-5,j-5);
circle(i,j,5);
if (attempt!=null){
// iterate a bit to see if it goes to 0
let [ai,aj] = attempt;
noFill();
stroke("red");
beginShape();
for (let t=0;t<10;t++){
if (t==0)
curveVertex(ai,aj);
curveVertex(ai,aj);
x = map(ai,0,width,-zoom,zoom);
y = map(aj,0,height,-zoom,zoom);
[xx,yy] = f(poly,x,y,1);
if (t==0){
push();
noStroke();
fill("red");
text(~~(x*10)/10+','+~~(y*10)/10,ai-5,aj-5);
pop();
}
ai = map(xx,-zoom,zoom,0,width);
aj = map(yy,-zoom,zoom,0,height);
}
curveVertex(ai,aj);
curveVertex(ai,aj);
endShape();
noStroke();
fill("purple")
circle(ai,aj,5);
}
}
function f(poly,x,y,scaling){
// test 0 return [5*sin(x),5*sin(y)];
let z=new Complex(x,y);
let p = `${poly.value()};`;
//console.log(p,z.toString(),z);
let F;
try {
F = eval(p);
F = F.mul(scaling);
//console.log(F);
} catch(e){
//console.log("Error:" + e);
F = new Complex(0,0);
}
return [F.re,F.im];
}
function _clicked(){
attempt = [mouseX,mouseY];
}
function _changed(){
attempt = null;
}
function mask(){
rect(0,0,width,height);
}