source("http://macosa.dima.unige.it/r.R") # If I have not already loaded the library ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- # For what positive value of x x^2 = 2 ? # I have to look for x such that x^2 - 2 = 0 f = function(x) x^2-2 graphF(f, -3,3, "blue") # Between 0 and 2 the graph of f cross the x axis. # I define a procedure that bisects the interval and selects the subinterval in which # F changes the sign. Zero=function(f,a,b) {m=a+(b-a)/2;y1=sign(f(a));y2=sign(f(m)); if(y1==y2) a<<- m else b<<- m} # In a and b the extremes of this subinterval are stored a=0;b=2 Zero(f,a,b); c(a,b) # 1 2 Zero(f,a,b); c(a,b) # 1.0 1.5 Zero(f,a,b); c(a,b) # 1.25 1.50 Zero(f,a,b); c(a,b) # 1.375 1.500 # ... Zero(f,a,b); c(a,b) # 1.414213 1.414214 Zero(f,a,b); c(a,b) # 1.414214 1.414214 # # The procedure "solution" automates this process. # # NOTE. Why (to calculate the mean of a and b) we use a+(b-a)/2 instead of (a+b)/2 ? # If I use a calculator with an 8-digit display (that works with 8 digits) for # computing (5.0000001 + 5.0000003) / 2 I obtain 10.00000/2 and then 5; if I # compute (5.0000003 + 5.0000004) / 2 I obtain 10.00001/2 and the 5.0000005. # I get results that are out of [a,b]. # If I use a+(b-a)/2 I cannot get values outside [a,b].