xxxxxxxxxx
114
let xMin = -1;
let xMax = 3.5;
let yMin = -4;
let yMax = 2;
let xScale = 1;
let yScale = 1;
let a = 1;
let b = 3;
// 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/2);
}
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/yScale);
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(6/yScale);
stroke('red');
point(a, 0);
stroke('blue');
point(b, 0);
BisectionMethod();
}
let i = 1; // counts the iterations of the method
let c = 0; // c will be the midpoint value of a and b in the bisection method
function BisectionMethod() {
let n = 100; // to avoid an infinite loop
let fc = f(c);
let tol = 0.01; //tolerance of the method
if (i <= n) {
console.log("\nBisection Method:");
console.log("a = " + a + "\t\tb = " + b);
c = (a + b) / 2; // middle of interval (a, b)
fc = f(c);
console.log("f(" + c + ") = " + f(c));
if (fc == 0 || (b - a) / 2 < tol) {
console.log("The root approximation is: " + c);
console.log("The number of steps is: " + i);
i = n + 1;
}
i++;
if (f(a) < f(b)) { // f increaseing from a to b
if (fc < 0) {
a = c;
}
else {
b = c;
}
}
else if (f(a) > f(b)) { // f decreasing from a to b
if (fc > 0) {
a = c;
}
else {
b = c;
}
}
}
} // end of Bisection Method