xxxxxxxxxx
73
const functions = {
squareRoot: {
function: function(x) {
return sqrt(x);
},
derivative: function(x) {
return 1 / (2 * sqrt(x));
}
},
cubic1: {
function: function(x) {
return pow(x, 3) - x + 1;
},
derivative: function(x) {
return 3 * pow(x, 2) - 1;
}
},
generalQuadratic: {
function: function(x, args) {
const a = args.a,
b = args.b,
c = args.c;
return a * pow(x, 2) + b * x + c;
},
derivative: function(x, args) {
const a = args.a,
b = args.b,
c = args.c;
return 2 * a * x + b;
}
}
};
function setup() {
createCanvas(640, 480);
}
function draw() {
background(255);
translate(width / 2, height / 2);
drawAxes();
const args = {
a: 1,
b: 1,
c: 1
};
graph(functions.generalQuadratic.function, color(255, 0, 0), args);
graph(functions.generalQuadratic.derivative, color(0, 255, 0), args);
}
function drawAxes() {
push();
stroke(0);
strokeWeight(3);
line(-width * 100, 0, width * 100, 0);
line(0, -height * 100, 0, height * 100);
pop();
}
function graph(func, col, args) {
push();
noFill();
stroke(col);
strokeWeight(3);
beginShape();
for (let x = -width; x <= width; x += 0.05) {
if (!isNaN(func(x, args))) {
vertex(x, -10 * func(x / 30, args));
}
}
endShape();
pop();
}