PVector Origin, Scale; PVector[] wv = new PVector[3]; PVector[] sv = new PVector[3]; PFont fontA; float x, y; int h=1; void setup() { size(500,500); smooth(); noLoop(); Origin = new PVector(300, 100); Scale = new PVector(50, 50); for(int i=0; i<3; i++) { wv[i] = new PVector(0, 0); sv[i] = new PVector(20, 20); } fontA = loadFont("ComicSansMS-Bold-32.vlw"); textAlign(CENTER); textFont(fontA, 8); } PVector World2Screen(PVector v){ // v.x=v.x*Scale.x+Origin.x; // v.y=height-v.y*Scale.y-Origin.y; v.mult(Scale); v.add(Origin); v.y=height-v.y; return v; } void draw() { background(200); fill(0); stroke(0); rectMode(CENTER); drawAxis(); drawFunction(); secant(5, 4, 0.000001); newtonraphson(5, 0.000001); bisection(-3, 4, 0.000001); } void secant(float xi, float xi_minus, float e) { int i=0; float xi_plus; while(abs(ft(xi)) > e) { xi_plus = xi - ft(xi)/ft_slope(xi,xi_minus); xi_minus = xi; xi = xi_plus; println("[Secant Iteration "+i+"]: The root is "+xi+" "); i++; } } void newtonraphson(float xi, float e) { int i=0; while(abs(ft(xi)) > e) { xi = xi - ft(xi)/ft_prime(xi); println("[NewtonRaphson Iteration "+i+"]: The root is "+xi+" "); i++; } } void bisection(float xl, float xh, float e) { float xm; xm = (ft(xh)*xl - ft(xl)*xh) / (ft(xh) - ft(xl)); // xm = (xh + xl) / 2.0; if(ft(xm) == (float)0) return; else if((ft(xm)*ft(xl)) < (float)0) xh = xm; else if((ft(xm)*ft(xh)) < (float)0) xl = xm; else { println("Something worng --> cannot find the root."); return; } println("[Recursion " + h + "]: The root is " + xm + " "); h++; if((xh - xl) <= e) return; else bisection(xl, xh, e); } void drawFunction() { float x=-1, y; y=ft(x); wv[0].set(x,y,0); sv[0]=World2Screen(wv[0]); for(x=-3; x<5; x+=0.025) { y=ft(x); wv[1].set(x,y,0); sv[1]=World2Screen(wv[1]); line(sv[0].x, sv[0].y, sv[1].x, sv[1].y); sv[0].set(sv[1].x, sv[1].y, 0); } } void drawAxis() { sv[0]=World2Screen(wv[0]); ellipse(sv[0].x, sv[0].y, 5, 5); text("O", sv[0].x-5, sv[0].y+10); wv[0].set(-3,0,0); wv[1].set(5,0,0); sv[0]=World2Screen(wv[0]); sv[1]=World2Screen(wv[1]); line(sv[0].x, sv[0].y, sv[1].x, sv[1].y); wv[0].set(0,-1,0); wv[1].set(0,5,0); sv[0]=World2Screen(wv[0]); sv[1]=World2Screen(wv[1]); line(sv[0].x, sv[0].y, sv[1].x, sv[1].y); for(int i=1; i<=5; i++) { wv[0].set(i,0,0); sv[0]=World2Screen(wv[0]); line(sv[0].x, sv[0].y-5, sv[0].x, sv[0].y+5); text(i, sv[0].x, sv[0].y+15); } for(int i=1; i<=5; i++) { wv[0].set(0,i,0); sv[0]=World2Screen(wv[0]); line(sv[0].x-5, sv[0].y, sv[0].x+5, sv[0].y); text(i, sv[0].x-15, sv[0].y); } } float ft(float x) { return log(x+5)+x; } float ft_prime(float x) { return 1/(x+5)+1; } float ft_slope(float x1, float x2) { return ((ft(x1)-ft(x2))/(x1-x2)); }