xxxxxxxxxx
107
let xMin = -1;
let xMax = 4;
let yMin = -4;
let yMax = f(2.5);
let xScale = 1;
let yScale = 1;
let a = 1.8;
let b = 2.5;
// f(x) = x^5 - 2x^4 - 1
function f(x) {
return x*x*x*x*x - 2*x*x*x*x - 1;
}
// Loop to graph points of f(x)
function graphF() {
stroke('green');
for(let x = xMin; x <= xMax; x += 0.0001) {
let y = f(x);
point(x, y);
}
}
function setup() {
createCanvas(800, 800);
xScale = width / (xMax - xMin);
yScale = height / (yMax - yMin);
// Slow down animation
frameRate(1/3);
}
function draw() {
background(220);
strokeWeight(3);
// Set display location and size based on x and y max and min & cavas size.
translate(width * (0 - xMin)/(xMax - xMin), height * yMax/(yMax - yMin));
scale(xScale, -yScale);
// Draw axes
stroke(0);
strokeWeight(1/yScale);
line(-width/2, 0, width/2, 0); //x-axis
strokeWeight(1/xScale);
line(0, height/2, 0, -height/2); //y-axis
// Draw tick marks on x-axis
strokeWeight(4/xScale);
stroke(0);
let min = Math.floor(xMin);
let max = Math.floor(xMax);
for(let x = min; x <= max; x++) {
point(x, 0);
}
// Graph function
strokeWeight(2/(xScale + yScale));
graphF();
/*** Plot points and functions below ***/
strokeWeight(10/xScale);
stroke('red');
point(a, 0);
stroke('blue');
point(b, 0);
strokeWeight(2/xScale);
stroke('orange');
line(a, f(a), b, f(b));
SecantMethod();
stroke(random())
}
let i = 1; // counts the iterations of the method
let c = 0; // c will be the root of the secant
//Secant Method for Root Finding
// from initial guess a and b
// each iteration a --> b, b --> c
function SecantMethod() {
let n = 100; // to avoid an infinite loop
let tol = 0.001; //tolerance of the method
if (i <= n) {
console.log("\nSecant Method " + i + ":");
console.log("a = " + a + "\t\tb = " + b);
c = b - f(b) * (b - a) / (f(b) - f(a)); // zero of the secant line
console.log("f(" + c + ") = " + f(c));
if (Math.abs(c - b) < tol) {
console.log("The root approximation is: " + c);
console.log("The number of steps is: " + i);
i = n + 1;
}
i++;
a = b;
b = c;
console.log(yMin + " " + yMax);
}
} // end of Secant Method